﻿Imports System.Data.SqlClient
Imports System.Globalization

Partial Public Class frm_ManageBooking
    Inherits System.Web.UI.Page

    Dim clsGet As New ClassFunctionGetData
    Dim clsFc As New ClassFunction
    Dim db As DB_Class
    Dim numberFormat As NumberFormatInfo
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        numberFormat = New NumberFormatInfo()
        db = New DB_Class()
        numberFormat.NumberDecimalDigits = 3
        If Not IsPostBack Then
            Dim lbPage As Label = CType(Master.FindControl("lbPage"), Label)
            lbPage.Text = "MANAGE BOOKING "

            Dim ClientName As String = Request.ServerVariables("http_user_agent")
            If (ClientName.Split("(")(1).Split(";")(0) = "compatible") Then
                panelGridItem.Width = 900
            Else
                panelGridItem.ScrollBars = ScrollBars.None
            End If
            Try
                If (Session("Role") & "" = "00004") Then
                    txtDateSearch.Text = Date.Now.ToString("dd MMM yyyy", New CultureInfo("en-US"))
                    txtDateSearchTo.Text = Date.Now.ToString("dd MMM yyyy", New CultureInfo("en-US"))
                End If
            Catch ex As Exception
                Response.Redirect("~/Form/logon.aspx")
            End Try

            ' Session("isFromSchedule") = Nothing
            Session("Operation") = Nothing
            Session("StandardTimePlus") = 0
            Dim Booking As String = Request.QueryString("booking")
            If Booking & "" = "" Then
                Session("Ship_View") = Nothing
                LoadBOoking()
                Timer1_Tick(sender, e)
                Session("isFromSchedule") = Nothing
                btnManageShiftingFromSchedule.Visible = False
                btnManageShifting.Visible = True
            Else
                ViewState("Owner") = ""
                EditBooking(CInt(Booking).ToString("#####00000"), "", "", "xx")
                Session("isFromSchedule") = True
                btnManageShiftingFromSchedule.Visible = True
                btnManageShifting.Visible = False
            End If
            txtBookingVPS.Attributes.Add("onkeypress", "return clickButton(event,'" + btnSearchVPS.ClientID + "')")
            txtShipVPS.Attributes.Add("onkeypress", "return clickButton(event,'" + btnSearchVPS.ClientID + "')")
            txtProductSearch.Attributes.Add("onkeypress", "return clickButton(event,'" + btnSearchVPS.ClientID + "')")

            txtBooking_no.Attributes.Add("onkeypress", "return clickButton(event,'" + btnSearchData.ClientID + "')")
            txtShipName.Attributes.Add("onkeypress", "return clickButton(event,'" + btnSearchData.ClientID + "')")
            txtMainAgentSearch.Attributes.Add("onkeypress", "return clickButton(event,'" + btnSearchData.ClientID + "')")
        End If
    End Sub

    Private Sub LoadBOoking()
        PanelBookingItem.Visible = True
        PanelDetailVPS_MRI.Visible = False
        Dim ds As DataSet
        If (Session("Role") & "" = "00003") Then
            ds = clsGet.Get_BookingMarketing("", "", False, "", "0", "", "0", "'CV','CC','CM','CR','CA'", "", "")
            PanelBookingItemAll.Visible = False
            PanelBookingItemMarketing.Visible = True
            If (ds.Tables(0).Rows.Count > 0) Then
                ViewState("Manage") = ds
                gridItemMarketing.DataSource = ViewState("Manage")
                gridItemMarketing.DataBind()
                lbAlertMarketing.Text = ""
            Else
                gridItemMarketing.DataSource = Nothing
                gridItemMarketing.DataBind()
                lbAlertMarketing.Text = "ไม่พบรายการ Booking"
            End If
        Else
            Dim DateFrom As String = ""
            Dim DateTo As String = ""
            'If (txtDateSearch.Text.Trim <> "") And (txtDateToSearch.Text.Trim() <> "") Then
            '    DateFrom = txtDateSearch.Text.Split(" ")(2) & CDate(txtDateSearch.Text).ToString("MMdd")
            '    DateTo = txtDateToSearch.Text.Split(" ")(2) & CDate(txtDateToSearch.Text).ToString("MMdd")
            'End If
            If (ddlStatusVPS.SelectedValue = "C") Then
                ds = clsGet.Get_Booking("", "", "", "'CV','CC','CM','CR','CA'", True, ddlPORTVPS.SelectedValue.Replace("0", ""), txtShipVPS.Text, "", "", txtBookingVPS.Text, ddlDestinationSearch.SelectedValue, DateFrom, DateTo, txtProductSearch.Text)
            Else
                ds = clsGet.Get_Booking("", "", "", "", True, ddlPORTVPS.SelectedValue.Replace("0", ""), txtShipVPS.Text, "", "'CV','CC','CM','CR','CA'", txtBookingVPS.Text, ddlDestinationSearch.SelectedValue, DateFrom, DateTo, txtProductSearch.Text)
            End If
            If (txtDateSearch.Text <> "") And (txtDateSearchTo.Text <> "") Then
                Dim c As Integer = 0
                Dim dtTemp As DataTable = ds.Tables(0).Copy
                For i As Integer = 0 To ds.Tables(0).Rows.Count - 1
                    Dim dtLogin As DataTable = clsGet.Get_BookingWharf(ds.Tables(0).Rows(i).Item("Booking_no"))
                    Try
                        If (CDate(dtLogin.Rows(0).Item("Date_From")) > CDate(txtDateSearch.Text)) Then
                            If (CDate(dtLogin.Rows(0).Item("Date_From")) > CDate(txtDateSearchTo.Text)) Then
                                dtTemp.Rows(i - c).Delete()
                                dtTemp.AcceptChanges()
                                c += 1
                            End If
                        ElseIf (CDate(dtLogin.Rows(0).Item("Date_To")) < CDate(txtDateSearch.Text)) Then
                            dtTemp.Rows(i - c).Delete()
                            dtTemp.AcceptChanges()
                            c += 1
                        End If
                        'If (dtLogin.Rows(0).Item("Date_From") <> txtDateSearch.Text) Then
                        '    dtTemp.Rows(i - c).Delete()
                        '    dtTemp.AcceptChanges()
                        '    c += 1
                        'End If
                    Catch ex As Exception
                        dtTemp.Rows(i - c).Delete()
                        dtTemp.AcceptChanges()
                        c += 1
                    End Try
                Next
                ds.Tables.Clear()
                ds.Tables.Add(dtTemp.Copy)
                ds.AcceptChanges()
            End If
            If (ddlProductLD.SelectedValue <> "A") Then
                Dim dsTemp As DataSet = ds.Copy
                Dim count As Integer = 0
                For i As Integer = 0 To ds.Tables(0).Rows.Count - 1
                    Dim dt As DataTable = clsGet.Get_Booking_Product(ds.Tables(0).Rows(i).Item("Booking_no"))
                    If (dt.Rows.Count > 0) Then
                        If (dt.Rows(0).Item("Product_Event") & "" <> ddlProductLD.SelectedValue) Then
                            dsTemp.Tables(0).Rows(i - count).Delete()
                            dsTemp.AcceptChanges()
                            count += 1
                        End If
                    Else
                        dsTemp.Tables(0).Rows(i - count).Delete()
                        dsTemp.AcceptChanges()
                        count += 1
                    End If
                Next
                ds = dsTemp
            End If
            If (ddlStatusVPS.SelectedValue = "P") Then
                Dim dsTemp As DataSet = ds.Copy
                Dim count As Integer = 0
                For i As Integer = 0 To ds.Tables(0).Rows.Count - 1
                    If (Session("Role") & "" = "00004") Then
                        If (ds.Tables(0).Rows(i).Item("VPS_approve") & "" <> "") Then
                            If Not ((ds.Tables(0).Rows(i).Item("Status") & "" <> "VC") And (ds.Tables(0).Rows(i).Item("Status") & "" <> "VP") And (ds.Tables(0).Rows(i).Item("Status") & "" <> "NB")) Then
                                dsTemp.Tables(0).Rows(i - count).Delete()
                                dsTemp.AcceptChanges()
                                count += 1
                            End If
                        Else
                            dsTemp.Tables(0).Rows(i - count).Delete()
                            dsTemp.AcceptChanges()
                            count += 1
                        End If
                    ElseIf (Session("Role") & "" = "00005") Then
                        If (ds.Tables(0).Rows(i).Item("MRI_approve") & "" <> "") Then
                            If Not ((ds.Tables(0).Rows(i).Item("Status") & "" <> "MC") And (ds.Tables(0).Rows(i).Item("Status") & "" <> "MP") And (ds.Tables(0).Rows(i).Item("Status") & "" <> "NB")) Then
                                dsTemp.Tables(0).Rows(i - count).Delete()
                                dsTemp.AcceptChanges()
                                count += 1
                            End If
                        Else
                            dsTemp.Tables(0).Rows(i - count).Delete()
                            dsTemp.AcceptChanges()
                            count += 1
                        End If
                    End If
                Next
                ds = dsTemp
                ds.AcceptChanges()
            ElseIf (ddlStatusVPS.SelectedValue = "W") Then
                Dim dsTemp As DataSet = ds.Copy
                Dim count As Integer = 0
                For i As Integer = 0 To ds.Tables(0).Rows.Count - 1
                    If (Session("Role") & "" = "00004") Then
                        If (ds.Tables(0).Rows(i).Item("VPS_approve") & "" <> "") Then
                            If ((ds.Tables(0).Rows(i).Item("Status") & "" <> "VC") And (ds.Tables(0).Rows(i).Item("Status") & "" <> "VP") And (ds.Tables(0).Rows(i).Item("Status") & "" <> "NB")) Then
                                dsTemp.Tables(0).Rows(i - count).Delete()
                                dsTemp.AcceptChanges()
                                count += 1
                            End If
                        End If
                    ElseIf (Session("Role") & "" = "00005") Then
                        If (ds.Tables(0).Rows(i).Item("MRI_approve") & "" <> "") Then
                            If ((ds.Tables(0).Rows(i).Item("Status") & "" <> "MC") And (ds.Tables(0).Rows(i).Item("Status") & "" <> "MP") And (ds.Tables(0).Rows(i).Item("Status") & "" <> "VA")) Then
                                dsTemp.Tables(0).Rows(i - count).Delete()
                                dsTemp.AcceptChanges()
                                count += 1
                            End If
                        End If
                    End If
                Next
                ds = dsTemp
            ElseIf (ddlStatusVPS.SelectedValue = "O") Then
                Dim dsTemp As DataSet = ds.Copy
                Dim count As Integer = 0
                For i As Integer = 0 To ds.Tables(0).Rows.Count - 1
                    If (ds.Tables(0).Rows(i).Item("MKT_Product") & "" = "Y") Then
                        dsTemp.Tables(0).Rows(i - count).Delete()
                        dsTemp.AcceptChanges()
                        count += 1
                    End If
                Next
                ds = dsTemp
            ElseIf (ddlStatusVPS.SelectedValue = "U") Then
                Dim dsTemp As DataSet = ds.Copy
                Dim count As Integer = 0
                For i As Integer = 0 To ds.Tables(0).Rows.Count - 1
                    If (ds.Tables(0).Rows(i).Item("MKT_Custom") & "" = "Y") Then
                        dsTemp.Tables(0).Rows(i - count).Delete()
                        dsTemp.AcceptChanges()
                        count += 1
                    End If
                Next
                ds = dsTemp
            ElseIf (ddlStatusVPS.SelectedValue = "F") Then
                Dim dsTemp As DataSet = ds.Copy
                Dim count As Integer = 0
                For i As Integer = 0 To ds.Tables(0).Rows.Count - 1
                    If (ds.Tables(0).Rows(i).Item("MKT_Finance") & "" = "Y") Then
                        dsTemp.Tables(0).Rows(i - count).Delete()
                        dsTemp.AcceptChanges()
                        count += 1
                    End If
                Next
                ds = dsTemp
            ElseIf (ddlStatusVPS.SelectedValue = "B") Then
                Dim dsTemp As DataSet = ds.Copy
                Dim count As Integer = 0
                For i As Integer = 0 To ds.Tables(0).Rows.Count - 1
                    Dim dtBerth As DataTable = clsGet.Get_Booking_LogSheet_In(ds.Tables(0).Rows(i).Item("Booking_no"))
                    If (dtBerth.Rows.Count > 0) Then
                        If (dtBerth.Rows(0).Item("Berthing_Date") & "" = "") Then
                            dsTemp.Tables(0).Rows(i - count).Delete()
                            dsTemp.AcceptChanges()
                            count += 1
                        End If
                    Else
                        dsTemp.Tables(0).Rows(i - count).Delete()
                        dsTemp.AcceptChanges()
                        count += 1
                    End If
                Next
                ds = dsTemp
            ElseIf (ddlStatusVPS.SelectedValue = "D") Then
                Dim dsTemp As DataSet = ds.Copy
                Dim count As Integer = 0
                For i As Integer = 0 To ds.Tables(0).Rows.Count - 1
                    Dim dtBerth As DataTable = clsGet.Get_Booking_LogSheet_Out(ds.Tables(0).Rows(i).Item("Booking_no"))
                    If (dtBerth.Rows.Count > 0) Then
                        If (dtBerth.Rows(0).Item("Last_Date") & "" = "") Then
                            dsTemp.Tables(0).Rows(i - count).Delete()
                            dsTemp.AcceptChanges()
                            count += 1
                        End If
                    Else
                        dsTemp.Tables(0).Rows(i - count).Delete()
                        dsTemp.AcceptChanges()
                        count += 1
                    End If
                Next
                ds = dsTemp
            End If
            ds.AcceptChanges()
            PanelBookingItemAll.Visible = True
            PanelBookingItemMarketing.Visible = False
            If (ds.Tables(0).Rows.Count > 0) Then
                ds.Tables(0).Columns.Add("Lay", GetType(String))
                ds.AcceptChanges()
                For i As Integer = 0 To ds.Tables(0).Rows.Count - 1
                    ds.Tables(0).Rows(i).Item("Lay") = CDate(ds.Tables(0).Rows(i).Item("Date_From")).ToString("yyyyMMdd")
                    ds.Tables(0).AcceptChanges()
                Next
                Dim dsView As DataView = ds.Tables(0).DefaultView
                dsView.Sort = " Lay DESC"
                ds = New DataSet
                ds.Tables.Add(clsGet.ConvertDataViewToDataSet(dsView).Copy)
                ViewState("Manage") = ds
                gridItem.DataSource = ViewState("Manage")
                gridItem.DataBind()
                lbAlert.Text = ""
                btnApproveAll.Visible = True

            Else
                gridItem.DataSource = Nothing
                gridItem.DataBind()
                lbAlert.Text = "ไม่พบรายการ Booking"
                btnApproveAll.Visible = False
            End If
        End If

    End Sub

    Private Sub EditBooking(ByVal Booking As String, ByVal Customer_no As String, ByVal Customer_name As String, ByVal Marketing_approve As String)
        radioPayin.Enabled = True
        ddlStatus.Items.Clear()
        Accordion1.SelectedIndex = 0
        Accordion2.SelectedIndex = -1

        Accordion4.SelectedIndex = -1
        If (Session("Role") & "" = "00004") Then
            MyAccordion.SelectedIndex = 0
            Accordion3.SelectedIndex = 0
        Else
            MyAccordion.SelectedIndex = -1
            Accordion3.SelectedIndex = -1
        End If
        Accordion5.SelectedIndex = -1

        ViewState("EditBooking") = Booking
        lbBooking_no.Text = Booking
        PanelBookingItem.Visible = False
        PanelDetailVPS_MRI.Visible = True
        panelCancelAcknowledge.Visible = False
        ' Dim dsBooking As DataSet = clsGet.Get_Booking(gridItem.DataKeys(Index).Values("Customer_no"), "", gridItem.DataKeys(Index).Values("Booking_no"), "", False)
        Dim dsBooking As DataSet = clsGet.Get_BookingOneRecord(Booking)
        ViewState("PORT") = dsBooking.Tables(0).Rows(0).Item("PORT") & ""

        Session("Shifting") = ViewState("EditBooking").ToString()
        Session("PORT") = ViewState("PORT").ToString()

        txtRemark.Text = String.Empty
        Dim Status As String = dsBooking.Tables(0).Rows(0).Item("Status") & ""
        If (ViewState("PORT") & "" = "L") Then
            Status = Status & ""
        Else
            If (Customer_no <> "") And (Customer_no <> dsBooking.Tables(0).Rows(0).Item("MAgent_no") & "") Then
                Dim dtstatus As DataTable = clsGet.Get_Booking_Product(ViewState("EditBooking"), Customer_no)
                If (dtstatus.Rows.Count > 0) Then
                    Status = dtstatus.Rows(0).Item("Status") & ""
                Else
                    Status = ""
                End If
                If (Status = "") Then
                    Status = "MA"
                End If
            Else
                Status = Status & ""
            End If
        End If
        If (Status & "" = "NB") Then
            ddlStatus.ClearSelection()
            ddlStatus.Items.Insert(0, "ยังไม่ได้เริ่มดำเนินการ")
            ddlStatus.Items.Insert(1, "ดำเนินการตรวจสอบ")
            ddlStatus.Items(1).Value = "VC"
            ddlStatus.Items.Insert(2, "พบปัญหาในการตรวจสอบ")
            ddlStatus.Items(2).Value = "VP"
        ElseIf ((Status & "" = "VC") Or (Status & "" = "VP")) Then
            ddlStatus.Items.Insert(0, "ดำเนินการตรวจสอบ")
            ddlStatus.Items(0).Value = "VC"
            ddlStatus.Items.Insert(1, "พบปัญหาในการตรวจสอบ")
            ddlStatus.Items(1).Value = "VP"
        ElseIf (Status & "" = "VA") Then
            ddlStatus.ClearSelection()
            ddlStatus.Items.Insert(0, "ยังไม่ได้เริ่มดำเนินการ")
            ddlStatus.Items.Insert(1, "ดำเนินการตรวจสอบ")
            ddlStatus.Items(1).Value = "MC"
            ddlStatus.Items.Insert(2, "พบปัญหาในการตรวจสอบ")
            ddlStatus.Items(2).Value = "MP"
        ElseIf ((Status & "" = "MC") Or (Status & "" = "MP")) Then
            ddlStatus.Items.Insert(0, "ดำเนินการตรวจสอบ")
            ddlStatus.Items(0).Value = "MC"
            ddlStatus.Items.Insert(1, "พบปัญหาในการตรวจสอบ")
            ddlStatus.Items(1).Value = "MP"
        End If

        Session("Product_popup") = clsGet.Get_Booking_Product(Booking)
        ViewState("Upload") = clsGet.Get_BookingUpload(Booking)
        Dim ProductName As String = ""
        Dim ProductAmount As Double = 0.0
        Dim ProductAmountByProduct As String = ""
        Dim ProductType As String = ""
        Dim Load As String = ""
        Dim Disch As String = ""
        Dim LoadIRPC As String = ""
        Dim DischIRPC As String = ""
        For Each dr As DataRow In CType(Session("Product_popup"), DataTable).Rows
            Select Case dr.Item("Product_Event") & ""
                Case "L" : Load = "Y"
                Case "D" : Disch = "Y"
                Case "R" : LoadIRPC = "Y"
                Case "I" : LoadIRPC = "Y"
            End Select
            If (dsBooking.Tables(0).Rows(0).Item("Vehicle_Destination") = "O") Then
                Session("Operation") = Load & "$" & Disch & "$" & LoadIRPC & "$" & DischIRPC & "$" & dsBooking.Tables(0).Rows(0).Item("Vehicle_Destination") & "$" & dsBooking.Tables(0).Rows(0).Item("Vehicle_TypeBuy")
            Else
                Session("Operation") = Load & "$" & Disch & "$" & LoadIRPC & "$" & DischIRPC & "$" & dsBooking.Tables(0).Rows(0).Item("Vehicle_Destination") & "$" & ""
            End If
            If (dr.Item("Product_name") & "" <> "") Then
                ProductName &= "," & dr.Item("Product_name")
                ProductAmount = ProductAmount + (CDbl(dr.Item("Product_Amount")))
                ProductType &= "," & dr.Item("Product_Unit")
                Dim ProductAmountProduct As Double = 0
                If (dr.Item("Product_Unit") & "" = "ML") Then
                    ProductAmountProduct = (CDbl(dr.Item("Product_Amount")) * 820).ToString("###############0.00")
                ElseIf (dr.Item("Product_Unit") & "" = "KB") Then
                    ProductAmountProduct = (CDbl(dr.Item("Product_Amount")) * 158.9873 * 0.8).ToString("###############0.00")
                Else
                    'MT
                    ProductAmountProduct = CDbl(dr.Item("Product_Amount"))
                End If
                ProductAmountByProduct &= dr.Item("Product_name") & "฿" & ProductAmountProduct.ToString("###############0.00") & "฿"
            End If
        Next
        Try
            Dim dtShifting As DataTable = clsGet.Get_BookingWharf(Booking)
            If (dtShifting.Rows.Count > 0) Then
                If (dtShifting.Rows(0).Item("Shift_Booking") & "" <> "") Then
                    Dim dtProductValue As DataTable = clsGet.Get_Booking_Product(dtShifting.Rows(0).Item("Shift_Booking") & "")
                    For Each dr As DataRow In dtProductValue.Rows
                        If (dr.Item("Product_name") & "" <> "") Then
                            ProductName &= "," & dr.Item("Product_name")
                            ProductAmount = ProductAmount + (CDbl(dr.Item("Product_Amount")))
                            ProductType &= "," & dr.Item("Product_Unit")
                            Dim ProductAmountProduct As Double = 0
                            If (dr.Item("Product_Unit") & "" = "ML") Then
                                ProductAmountProduct = (CDbl(dr.Item("Product_Amount")) * 820).ToString("###############0.00")
                            ElseIf (dr.Item("Product_Unit") & "" = "KB") Then
                                ProductAmountProduct = (CDbl(dr.Item("Product_Amount")) * 158.9873 * 0.8).ToString("###############0.00")
                            Else
                                'MT
                                ProductAmountProduct = CDbl(dr.Item("Product_Amount"))
                            End If
                            ProductAmountByProduct &= dr.Item("Product_name") & "฿" & ProductAmountProduct.ToString("###############0.00") & "฿"
                        End If
                    Next
                End If
            End If
        Catch ex As Exception

        End Try


        If (ProductName.Length > 0) Then
            ProductName = ProductName.Substring(1, ProductName.Length - 1)
            ProductType = ProductType.Substring(1, ProductType.Length - 1)
        End If
        Dim CheckVehicleFake As Boolean = False
        lbName.Text = dsBooking.Tables(0).Rows(0).Item("Booking_name")
        Dim NameAgent As String = ""
        Dim CodeAgent As String = ""

        txtid.Text = String.Empty
        txtAgent.Text = String.Empty

        If (Customer_no <> "") And (Customer_no <> dsBooking.Tables(0).Rows(0).Item("MAgent_no") & "") Then
            NameAgent = Customer_no & "-" & Customer_name & ""
            CodeAgent = Customer_no & ""
            txtid.Text = Customer_no & "-" & Customer_name
            txtBillTo.Text = ""
            AutoCompleteExtender3.ContextKey = CodeAgent
            Label23.Text = "เจ้าของสินค้า"
        Else
            Label23.Text = "Main Agent(SoldTo)"
            If (dsBooking.Tables(0).Rows(0).Item("MAgent_no") & "" <> "") Then
                NameAgent = dsBooking.Tables(0).Rows(0).Item("MAgent_no") & "-" & dsBooking.Tables(0).Rows(0).Item("MAgent_name") & ""
                CodeAgent = dsBooking.Tables(0).Rows(0).Item("MAgent_no") & ""
                txtid.Text = dsBooking.Tables(0).Rows(0).Item("MAgent_no") & "-" & dsBooking.Tables(0).Rows(0).Item("MAgent_name")
                AutoCompleteExtender3.ContextKey = CodeAgent
            End If
            If (dsBooking.Tables(0).Rows(0).Item("SAgent_no") & "" <> "") Then
                txtAgent.Text = dsBooking.Tables(0).Rows(0).Item("SAgent_no") & "-" & dsBooking.Tables(0).Rows(0).Item("SAgent_name")
            End If
            If (dsBooking.Tables(0).Rows(0).Item("Bill_To_no") & "" = "") Then
                txtBillTo.Text = String.Empty
            Else
                txtBillTo.Text = dsBooking.Tables(0).Rows(0).Item("Bill_To_no") & "-" & dsBooking.Tables(0).Rows(0).Item("Bill_To_Name")
                'txtBillTo.Enabled = False
            End If
        End If


        If (dsBooking.Tables(0).Rows(0).Item("Vehicle_no") & "" = "999999999") Then
            CheckVehicleFake = True
            lbVehicle.Text = dsBooking.Tables(0).Rows(0).Item("Vehicle_Text")
        Else
            lbVehicle.Text = dsBooking.Tables(0).Rows(0).Item("Vehicle_no") & "-" & dsBooking.Tables(0).Rows(0).Item("Vehicle_Text")
        End If
        rowLaycan.Visible = True
        rowLaycanChange.Visible = False
        btnSaveVPS_SaleMarketing.Visible = False
        rowApproveVps_SaleMKT.Visible = False
        If (Session("Role") & "" = "00003") Then
            'Marketing
            If CodeAgent & "" <> "" Then
                panelCreditLimit.Visible = True
                GetCreditLimit(CodeAgent)
            Else
                lbLimit.Text = "0.00"
                lbUse.Text = "0.00"
                lbSalesValue.Text = "0.00"
                lbTotal.Text = "0.00"
                lbAvailable.Text = "0.00"
            End If

            Dim Payin As String = ""
            ' If (Status & "" = "MO") Then
            If (Marketing_approve & "" <> "") Then
                'radioPayin.Enabled = False
                btnComputeOld.Visible = True
                Payin = dsBooking.Tables(0).Rows(0).Item("Payin") & ""
            ElseIf (Status & "" = "OA") Or (Status & "" = "FN") Then
                radioPayin.Enabled = False
                btnCompute.Visible = False
                btnComputeOld.Visible = True
                btnCancle2.Visible = False
                Payin = dsBooking.Tables(0).Rows(0).Item("Payin") & ""
            Else
                btnComputeOld.Visible = False
                btnCompute.Visible = True
                ' Payin = clsGet.Get_DefaultPayin(lbMainAgent.Text.Split("-")(0))
                Payin = clsGet.Get_DefaultPayin(dsBooking.Tables(0).Rows(0).Item("MAgent_no") & "")
            End If
            If Not (radioPayin.Items.FindByValue(Payin) Is Nothing) Then
                radioPayin.SelectedValue = Payin
            End If
            gridTariff.Columns(0).Visible = True
            '  gridTariff.Columns(3).Visible = False
            gridTariff.Columns(4).Visible = True
            gridTariff.Columns(12).Visible = True
            rowTariff.Visible = True
            PanelMarketing_Action.Visible = True
            PanelVPS_MRI_APPROVE.Visible = False
            PanalSaleMKT.Visible = False
            lbLOA.Text = dsBooking.Tables(0).Rows(0).Item("Vehicle_LOA")
            lbDraft.Text = dsBooking.Tables(0).Rows(0).Item("Vehicle_Draft")
            lbDWT.Text = dsBooking.Tables(0).Rows(0).Item("Vehicle_DWT")
            lbGRT.Text = dsBooking.Tables(0).Rows(0).Item("Vehicle_GRT")
            lbNation.Text = dsBooking.Tables(0).Rows(0).Item("Vehicle_CNTRY")
            Dim nation As String = "O"
            If (lbNation.Text = "TH") Then
                nation = "T"
            End If
            Dim standardTimePlus As Integer = 0
            If (dsBooking.Tables(0).Rows(0).Item("BunkerFO_chk") & "" = "Y") Then
                standardTimePlus = standardTimePlus + (CInt(dsBooking.Tables(0).Rows(0).Item("BunkerFO_Point")) * 45)
            End If
            If (dsBooking.Tables(0).Rows(0).Item("BunkerDO_chk") & "" = "Y") Then
                standardTimePlus = standardTimePlus + (CInt(dsBooking.Tables(0).Rows(0).Item("BunkerDO_Point")) * 45)
            End If
            Session("StandardTimePlus") = standardTimePlus
            ' Session("Value") = dsBooking.Tables(0).Rows(0).Item("Vehicle_LOA") & "$" & dsBooking.Tables(0).Rows(0).Item("Vehicle_DWT") & "$" & dsBooking.Tables(0).Rows(0).Item("Vehicle_Draft") & "$" & dsBooking.Tables(0).Rows(0).Item("Vehicle_GRT") & "$" & dsBooking.Tables(0).Rows(0).Item("Vehicle_Text") & "$" & dsBooking.Tables(0).Rows(0).Item("Customer_name") & "$Actimate" & "$" & ProductName & "$" & ProductAmount & "$" & ProductAmountByProduct
            Session("Value") = NameAgent & "$" & dsBooking.Tables(0).Rows(0).Item("Vehicle_Text") & "$" & ProductName & "$" & dsBooking.Tables(0).Rows(0).Item("Vehicle_DWT") & "$" & dsBooking.Tables(0).Rows(0).Item("Vehicle_LOA") & "$" & ProductAmount & "$" & dsBooking.Tables(0).Rows(0).Item("Vehicle_Draft") & "$Actual$" & dsBooking.Tables(0).Rows(0).Item("Vehicle_Destination") & "$" & dsBooking.Tables(0).Rows(0).Item("Vehicle_TypeBuy") & "$" & nation & "$" & dsBooking.Tables(0).Rows(0).Item("Vehicle_GRT") & "$" & dsBooking.Tables(0).Rows(0).Item("PORT") & "$" & ProductAmountByProduct & "$" & CodeAgent
        ElseIf (Session("Role") & "" = "00007") Then
            'MKT ฝ่ายขาย
            PanelMarketing_Action.Visible = False
            PanelVPS_MRI_APPROVE.Visible = False
            PanalSaleMKT.Visible = True
            rowLaycan.Visible = False
            rowLaycanChange.Visible = True
            txtDate.Text = dsBooking.Tables(0).Rows(0).Item("Date_From")
            txtDateTo.Text = dsBooking.Tables(0).Rows(0).Item("Date_To")

            If (dsBooking.Tables(0).Rows(0).Item("MKT_Product") & "" = "Y") Then
                chkApprove.Items(0).Selected = True
            Else
                chkApprove.Items(0).Selected = False
            End If
            If (dsBooking.Tables(0).Rows(0).Item("MKT_Custom") & "" = "Y") Then
                chkApprove.Items(1).Selected = True
            Else
                chkApprove.Items(1).Selected = False
            End If
            If (dsBooking.Tables(0).Rows(0).Item("MKT_Finance") & "" = "Y") Then
                chkApprove.Items(2).Selected = True
            Else
                chkApprove.Items(2).Selected = False
            End If

        ElseIf (Session("Role") & "" = "00008") Then
            'Finance
            btnCompute.Visible = False
            btnCancle2.Visible = False
            If CodeAgent & "" <> "" Then
                panelCreditLimit.Visible = True
                GetCreditLimit(CodeAgent)
            Else
                lbLimit.Text = "0.00"
                lbUse.Text = "0.00"
                lbSalesValue.Text = "0.00"
                lbTotal.Text = "0.00"
                lbAvailable.Text = "0.00"
            End If
            Dim Payin As String = ""
            If (Status & "" = "MO") Then
                radioPayin.Enabled = False
                Payin = dsBooking.Tables(0).Rows(0).Item("Payin") & ""
            Else
                ' Payin = clsGet.Get_DefaultPayin(lbMainAgent.Text.Split("-")(0))
                Payin = clsGet.Get_DefaultPayin(dsBooking.Tables(0).Rows(0).Item("MAgent_no") & "")
            End If
            If Not (radioPayin.Items.FindByValue(Payin) Is Nothing) Then
                radioPayin.SelectedValue = Payin
            End If
            PanelMarketing_Action.Visible = True
            PanelVPS_MRI_APPROVE.Visible = False
            PanalSaleMKT.Visible = False
            lbLOA.Text = dsBooking.Tables(0).Rows(0).Item("Vehicle_LOA")
            lbDraft.Text = dsBooking.Tables(0).Rows(0).Item("Vehicle_Draft")
            lbDWT.Text = dsBooking.Tables(0).Rows(0).Item("Vehicle_DWT")
            lbGRT.Text = dsBooking.Tables(0).Rows(0).Item("Vehicle_GRT")
            lbNation.Text = dsBooking.Tables(0).Rows(0).Item("Vehicle_CNTRY")
        Else
            gridTariff.Columns(0).Visible = False
            ' gridTariff.Columns(3).Visible = False
            'gridTariff.Columns(4).Visible = False
            'gridTariff.Columns(5).Visible = False
            gridTariff.Columns(12).Visible = False
            rowTariff.Visible = False
            PanelMarketing_Action.Visible = False
            PanelVPS_MRI_APPROVE.Visible = True
            PanalSaleMKT.Visible = False
        End If

        If (Session("Role") & "" = "00004") Then 'VPS
            If Not ((Status & "" = "NB") Or (Status & "" = "VC") Or (Status & "" = "VP")) Then
                If ((Status & "" = "CC") Or (Status & "" = "CM") Or (Status & "" = "CR") Or (Status & "" = "CA") Or (Status & "" = "CV")) Then
                    If (dsBooking.Tables(0).Rows(0).Item("Vps_Acknowledge") & "" = "") And (Status & "" <> "CV") Then
                        If (Status & "" = "CC") Then
                            btnCancelByCustomer.Visible = True
                            btnAcknowledge.Visible = False
                        Else
                            btnCancelByCustomer.Visible = False
                            btnAcknowledge.Visible = True
                        End If
                        panelCancelAcknowledge.Visible = True
                        PanelBack.Visible = False
                        PanelVPS_MRI_APPROVE.Visible = False
                    Else
                        panelCancelAcknowledge.Visible = False
                        PanelBack.Visible = True
                        PanelVPS_MRI_APPROVE.Visible = False
                    End If
                    rowCancel.Visible = True
                Else
                    rowCancel.Visible = False
                    panelCancelAcknowledge.Visible = False
                    PanelBack.Visible = True
                    PanelVPS_MRI_APPROVE.Visible = False
                    btnSaveVPS_SaleMarketing.Visible = True
                    rowApproveVps_SaleMKT.Visible = True
                    If (dsBooking.Tables(0).Rows(0).Item("MKT_Product") & "" = "Y") Then
                        chkApproveForVPS.Items(0).Selected = True
                    Else
                        chkApproveForVPS.Items(0).Selected = False
                    End If
                    If (dsBooking.Tables(0).Rows(0).Item("MKT_Custom") & "" = "Y") Then
                        chkApproveForVPS.Items(1).Selected = True
                    Else
                        chkApproveForVPS.Items(1).Selected = False
                    End If
                    If (dsBooking.Tables(0).Rows(0).Item("MKT_Finance") & "" = "Y") Then
                        chkApproveForVPS.Items(2).Selected = True
                    Else
                        chkApproveForVPS.Items(2).Selected = False
                    End If

                End If

            Else
                PanelBack.Visible = False
            End If
        ElseIf (Session("Role") & "" = "00005") Then
            If (CheckVehicleFake) Then
                'แสดงว่าเป็นเรือ ที่ไม่มีในระบบ
                rowVehicle.Visible = True
            Else
                rowVehicle.Visible = False
            End If
            If (dsBooking.Tables(0).Rows(0).Item("Remark_VPS") & "").ToString().Trim() <> "" Then
                rowRemarkVPS.Visible = True
            Else
                rowRemarkVPS.Visible = False
            End If
            If Not ((Status & "" = "VA") Or (Status & "" = "MC") Or (Status & "" = "MP")) Then
                PanelBack.Visible = True
                btnCancelBookingView.Visible = False
                PanelVPS_MRI_APPROVE.Visible = False
            Else
                PanelBack.Visible = False
            End If
        ElseIf (Session("Role") & "" = "00003") Then
            ' If Not ((Status & "" = "MA") Or (Status & "" = "MO")) Then
            If Not (Marketing_approve & "" <> "") Then
                If ((Status & "" = "CA") Or (Status & "" = "CV") Or (Status & "" = "CR") Or (Status & "" = "CC") Or (Status & "" = "CM")) Then
                    If (dsBooking.Tables(0).Rows(0).Item("MKT_Acknowledge") & "" = "") And (Status & "" = "CM") Then
                        panelCancelAcknowledge.Visible = True
                        PanelBack.Visible = False
                        PanelVPS_MRI_APPROVE.Visible = False
                        PanelMarketing_Action.Visible = False
                        rowTariff.Visible = False
                    Else
                        PanelBack.Visible = True
                        PanelVPS_MRI_APPROVE.Visible = False
                        PanelMarketing_Action.Visible = False
                        gridTariff.Columns(2).Visible = True
                        ' gridTariff.Columns(3).Visible = False
                        ' gridTariff.Columns(5).Visible = False
                        rowTariff.Visible = False
                    End If
                    rowCancel.Visible = True
                Else
                    If (Status & "" = "OA") Or (Status & "" = "FN") Then
                        rowCancel.Visible = False
                        PanelBack.Visible = False
                        PanelVPS_MRI_APPROVE.Visible = False
                        PanelMarketing_Action.Visible = True
                        gridTariff.Columns(2).Visible = True
                        ' gridTariff.Columns(3).Visible = False
                        ' gridTariff.Columns(5).Visible = False
                        rowTariff.Visible = False
                    Else
                        rowCancel.Visible = False
                        PanelBack.Visible = False
                        PanelVPS_MRI_APPROVE.Visible = False
                        'PanelMarketing_Action.Visible = False
                        gridTariff.Columns(2).Visible = True
                        ' gridTariff.Columns(3).Visible = False
                        ' gridTariff.Columns(5).Visible = False
                        rowTariff.Visible = True
                    End If

                End If
            Else
                PanelBack.Visible = False
            End If
        End If
        ViewState("Status_Pay") = dsBooking.Tables(0).Rows(0).Item("Status_Pay") & ""
        If Not (ddlStatus.Items.FindByValue(Status) Is Nothing) Then
            ddlStatus.SelectedValue = Status
        End If
        Select Case Status
            Case "CC"
                lbCancel.Text = "ลูกค้าประสงค์ทำการยกเลิก รอการยืนยันจากทาง VPS<br /> - " & dsBooking.Tables(0).Rows(0).Item("Cancel_Description")
                If (dsBooking.Tables(0).Rows(0).Item("Vps_Acknowledge") & "" <> "") Then
                    lbCancel.Text &= "<br /> VPS รับทราบการขอยกเลิกรายการจองแล้ว"
                End If
                If (dsBooking.Tables(0).Rows(0).Item("MKT_Acknowledge") & "" <> "") Then
                    lbCancel.Text &= "<br /> Marketing รับทราบการขอยกเลิกรายการจองแล้ว"
                End If
            Case "CR"
                lbCancel.Text = "ยกเลิกโดย MRI<br /> - " & dsBooking.Tables(0).Rows(0).Item("Cancel_Description")
                If (dsBooking.Tables(0).Rows(0).Item("Vps_Acknowledge") & "" <> "") Then
                    lbCancel.Text &= "<br /> VPS รับทราบการขอยกเลิกรายการจองแล้ว"
                End If
                If (dsBooking.Tables(0).Rows(0).Item("MKT_Acknowledge") & "" <> "") Then
                    lbCancel.Text &= "<br /> Marketing รับทราบการขอยกเลิกรายการจองแล้ว"
                End If
            Case "CM"
                lbCancel.Text = "ยกเลิกโดย Marketing<br /> - " & dsBooking.Tables(0).Rows(0).Item("Cancel_Description")
                If (dsBooking.Tables(0).Rows(0).Item("Vps_Acknowledge") & "" <> "") Then
                    lbCancel.Text &= "<br /> VPS รับทราบการขอยกเลิกรายการจองแล้ว"
                End If
            Case "CV"
                lbCancel.Text = "ยกเลิกโดย VPS<br /> - " & dsBooking.Tables(0).Rows(0).Item("Cancel_Description")
                If (dsBooking.Tables(0).Rows(0).Item("MKT_Acknowledge") & "" <> "") Then
                    lbCancel.Text &= "<br /> Marketing รับทราบการขอยกเลิกรายการจองแล้ว"
                End If
            Case "CA"
                lbCancel.Text = "ยกเลิกโดย VPS ตามคำร้องขอ ของลูกค้า<br /> - " & dsBooking.Tables(0).Rows(0).Item("Cancel_Description")
                If (dsBooking.Tables(0).Rows(0).Item("MKT_Acknowledge") & "" <> "") Then
                    lbCancel.Text &= "<br /> Marketing รับทราบการขอยกเลิกรายการจองแล้ว"
                End If
        End Select
        ShowRemark(dsBooking.Tables(0).Rows(0).Item("Booking_no"), True)
        Dim Agent As String = ""
        'If (Session("Role") & "" = "00003") Then
        '    If (ViewState("PORT") & "" = "B") Then

        '        If Not (rowMainAgentEmpty.Visible) Then
        '            Agent = lbMainAgent.Text.Split("-")(0)
        '            Dim Name As String = ""
        '            For i As Integer = 1 To lbMainAgent.Text.Split("-").Length - 1
        '                Name &= lbMainAgent.Text.Split("-")(i)
        '            Next
        '            gridTariff.Columns(5).HeaderText = Name
        '            ViewState("OwnerColumn") = Agent & "฿" & Name
        '        Else
        '            gridTariff.Columns(5).HeaderText = "SoldTo"
        '            ViewState("OwnerColumn") = "฿SoldTo"
        '        End If
        '        gridTariff.Columns(5).Visible = True
        '        Dim dt As DataTable = Session("Product_popup")
        '        Dim count As Integer = 6
        '        For Each dr As DataRow In dt.Rows
        '            If (dr.Item("Owner_Product_no") & "" <> "") Then
        '                Dim chk() As String = ViewState("OwnerColumn").ToString.Split("$")
        '                Dim chkDuplicate As Boolean = True
        '                For i As Integer = 0 To chk.Length - 1
        '                    If (chk(i) = dr.Item("Owner_Product_name") & "") Then
        '                        chkDuplicate = False
        '                    End If
        '                Next
        '                If (chkDuplicate) Then
        '                    ViewState("OwnerColumn") &= "$" & dr.Item("Owner_Product_no") & "฿" & dr.Item("Owner_Product_name")
        '                    gridTariff.Columns(count).Visible = True
        '                    gridTariff.Columns(count).HeaderText = dr.Item("Owner_Product_name")
        '                    count += 1
        '                End If
        '            End If
        '        Next
        '    End If
        'End If
        Dim dtTariff As DataSet = clsGet.Get_BookingTariff(dsBooking.Tables(0).Rows(0).Item("Booking_no"), Customer_no)
        If (dtTariff.Tables(0).Rows.Count = 0) Then
            dtTariff = clsGet.Get_BookingTariff(dsBooking.Tables(0).Rows(0).Item("Booking_no"), "X")
        End If
        Session("MAT_USE") = dtTariff
        gridTariff.DataSource = Session("MAT_USE")
        gridTariff.DataBind()

        If (Session("Role") & "" = "00003") Then
            btnReloadVessel.Visible = True
            Dim dsTariff As DataSet = Session("MAT_USE")
            ViewState("FREE") = True
            Dim Count As Double = 0.0
            For Each dr As DataRow In dsTariff.Tables(0).Rows
                Try
                    Count += CDbl(dr.Item("SumTotal") & "")
                Catch ex As Exception

                End Try
            Next
            If (Count > 0.0) Then
                ViewState("FREE") = False
                labelRed.Visible = True
            Else
                labelRed.Visible = False
            End If
        Else
            btnReloadVessel.Visible = False
        End If

        lbLOA.Text = dsBooking.Tables(0).Rows(0).Item("Vehicle_LOA")
        lbDWT.Text = dsBooking.Tables(0).Rows(0).Item("Vehicle_DWT")
        lbDraft.Text = dsBooking.Tables(0).Rows(0).Item("Vehicle_Draft")
        lbGRT.Text = dsBooking.Tables(0).Rows(0).Item("Vehicle_GRT")
        lbNation.Text = dsBooking.Tables(0).Rows(0).Item("Vehicle_CNTRY")
        lbDate.Text = dsBooking.Tables(0).Rows(0).Item("Date_From") & " ถึง " & dsBooking.Tables(0).Rows(0).Item("Date_To")
        lbBookingDateTime.Text = dsBooking.Tables(0).Rows(0).Item("Booking_Date") & " : " & dsBooking.Tables(0).Rows(0).Item("Booking_Time")
        lbLayTime.Text = dsBooking.Tables(0).Rows(0).Item("Lay_Time") & " hours"
        If (dsBooking.Tables(0).Rows(0).Item("Vehicle_Destination") = "I") Then
            lbDestination.Text = "DOMESTIC"
            rowTypeBuy.Visible = False
        Else
            lbDestination.Text = "FOREIGN"
            rowTypeBuy.Visible = True
            If (dsBooking.Tables(0).Rows(0).Item("Vehicle_TypeBuy") = "F") Then
                lbTypeBuy.Text = "FOB"
            ElseIf (dsBooking.Tables(0).Rows(0).Item("Vehicle_TypeBuy") = "C") Then
                lbTypeBuy.Text = "CFR"
            ElseIf (dsBooking.Tables(0).Rows(0).Item("Vehicle_TypeBuy") = "I") Then
                lbTypeBuy.Text = "CIF"
            Else
                lbTypeBuy.Text = "อื่นๆ"
            End If
            If (dsBooking.Tables(0).Rows(0).Item("Demurrage_Money") = "B") Then
                If (dsBooking.Tables(0).Rows(0).Item("Demurrage") & "" = "") Then
                    lbDemurrage.Text = "- BAHT"
                Else
                    lbDemurrage.Text = dsBooking.Tables(0).Rows(0).Item("Demurrage") & " BAHT "
                End If
            ElseIf (dsBooking.Tables(0).Rows(0).Item("Demurrage_Money") = "U") Then
                If (dsBooking.Tables(0).Rows(0).Item("Demurrage") & "" = "") Then
                    lbDemurrage.Text = "- USD"
                Else
                    lbDemurrage.Text = dsBooking.Tables(0).Rows(0).Item("Demurrage") & " USD "
                End If
            Else
                If (dsBooking.Tables(0).Rows(0).Item("Demurrage") & "" = "") Then
                    lbDemurrage.Text = "- PDPR"
                Else
                    lbDemurrage.Text = dsBooking.Tables(0).Rows(0).Item("Demurrage") & " PDPR "
                End If
            End If
        End If
        Dim Bunker As String = ""
        If (dsBooking.Tables(0).Rows(0).Item("BunkerFO_chk") & "" = "Y") Then
            rowBunker.Visible = True
            Bunker = " FO  " & dsBooking.Tables(0).Rows(0).Item("BunkerFO_Point") & " คัน "
            If (dsBooking.Tables(0).Rows(0).Item("BunkerDO_chk") & "" = "Y") Then
                Bunker &= "<br /> DO  " & dsBooking.Tables(0).Rows(0).Item("BunkerDO_Point") & " คัน"
                If (dsBooking.Tables(0).Rows(0).Item("BunkerDetail") & "" <> "") Then
                    Bunker &= "<br />  " & dsBooking.Tables(0).Rows(0).Item("BunkerDetail")
                End If
            Else
                If (dsBooking.Tables(0).Rows(0).Item("BunkerDetail") & "" <> "") Then
                    Bunker &= "<br />  " & dsBooking.Tables(0).Rows(0).Item("BunkerDetail")
                End If
            End If
        Else
            If (dsBooking.Tables(0).Rows(0).Item("BunkerDO_chk") & "" = "Y") Then
                rowBunker.Visible = True
                Bunker = " DO  " & dsBooking.Tables(0).Rows(0).Item("BunkerDO_Point") & " คัน"
                If (dsBooking.Tables(0).Rows(0).Item("BunkerDetail") & "" <> "") Then
                    Bunker &= "<br />  " & dsBooking.Tables(0).Rows(0).Item("BunkerDetail")
                End If
            Else
                rowBunker.Visible = False
            End If
        End If
        lbBunker.Text = Bunker
        If (dsBooking.Tables(0).Rows(0).Item("Water_Point") & "" <> "0") And (dsBooking.Tables(0).Rows(0).Item("Water_Point") & "" <> "") Then
            rowWater.Visible = True
            lbWater.Text = dsBooking.Tables(0).Rows(0).Item("Water_Point") & " TON"
        Else
            rowWater.Visible = False
        End If
        If (dsBooking.Tables(0).Rows(0).Item("Electricity") & "" <> "0") And (dsBooking.Tables(0).Rows(0).Item("Electricity") & "" <> "") Then
            rowElectrictity.Visible = True
            lbWater.Text = dsBooking.Tables(0).Rows(0).Item("Electricity") & " KWH"
        Else
            rowElectrictity.Visible = False
        End If
        Session("PORT_PRODUCT") = ViewState("PORT")
        If (dsBooking.Tables(0).Rows(0).Item("PORT") & "" = "B") Then
            lbPort.Text = "Bulk"
            gridProduct.Columns(5).Visible = False
            gridProduct.Columns(6).Visible = False
            gridProduct.Columns(7).Visible = True
        Else
            lbPort.Text = "Liquid"
            gridProduct.Columns(5).Visible = True
            gridProduct.Columns(6).Visible = True
            gridProduct.Columns(7).Visible = False
        End If
        gridProduct.PageIndex = 0
        gridProduct.DataSource = Session("Product_popup")
        gridProduct.DataBind()
        gridfile.PageIndex = 0
        gridfile.DataSource = ViewState("Upload")
        gridfile.DataBind()
        lbRemark.Text = dsBooking.Tables(0).Rows(0).Item("Remark")

        LoadShipSchedule()

    End Sub
    Protected Sub LoadShipSchedule()
        If (Session("Role").ToString() = "00004") Then
            'Dim dt As DataTable = clsGet.Get_BookingWharf(ViewState("EditBooking"))
            Dim bookingNo As String = ViewState("EditBooking").ToString()
            db = New DB_Class()
            db.queryString = "select * from BookingWharf bw left outer join Booking b on bw.Booking_no=b.Booking_no "
            db.queryString &= " left outer join Wharf w on bw.BookingWharf=w.BookingWharf"
            db.queryString &= " where bw.Booking_no='" & bookingNo & "'"
            Dim dtWharf As DataTable = db.getTable("wharf")
            Dim port As String = ViewState("PORT").ToString()
            Dim dtShift As DataTable = CloneBookingShiftingSchema()
            If (dtWharf.Rows.Count > 0) Then
                Dim drShift As DataRow = dtShift.NewRow()
                Dim drWharf As DataRow = dtWharf.Rows(0)
                drShift("Shifting_ID") = "00000"
                drShift("BookingWharf") = drWharf("BookingWharf").ToString()
                Dim dateStart As Date = Date.ParseExact(drWharf("DateStart").ToString(), "dd/MM/yyyy", New CultureInfo("en-US"))
                drShift("DateStart") = dateStart.ToString("dd MMM yyyy")
                Dim dateEnd As Date = Date.ParseExact(drWharf("DateEnd").ToString(), "dd/MM/yyyy", New CultureInfo("en-US"))
                drShift("DateEnd") = dateEnd.ToString("dd MMM yyyy")
                drShift("TimeStart") = drWharf("TimeStart").ToString()
                drShift("TimeEnd") = drWharf("TimeEnd").ToString()

                If (drWharf("Confirm_Time").ToString() = "Y") Then
                    drShift("Confirm_Time") = "YES"
                Else
                    drShift("Confirm_Time") = "NO"
                End If

                drShift("Remark") = drWharf("Remark").ToString()
                drShift("Note") = drWharf("Note").ToString()
                dtShift.Rows.Add(drShift)

            End If

            db.queryString = "select * from Booking_Shifting bs left outer join Booking b on bs.Booking_no=b.Booking_no"
            db.queryString &= " left outer join Wharf w on bs.BookingWharf=w.BookingWharf"
            db.queryString &= " where bs.Booking_no='" & bookingNo & "'"
            Dim dtShift2 As DataTable = db.getTable("shifting2")

            If (dtShift2.Rows.Count > 0) Then
                For Each drShift2 As DataRow In dtShift2.Rows
                    Dim drShift As DataRow = dtShift.NewRow()
                    drShift("Shifting_ID") = drShift2("Shifting_ID").ToString()
                    drShift("BookingWharf") = drShift2("BookingWharf").ToString()
                    Dim dateStart As Date = Date.ParseExact(drShift2("DateStart").ToString(), "dd/MM/yyyy", New CultureInfo("en-US"))
                    drShift("DateStart") = dateStart.ToString("dd MMM yyyy")
                    Dim dateEnd As Date = Date.ParseExact(drShift2("DateEnd").ToString(), "dd/MM/yyyy", New CultureInfo("en-US"))
                    drShift("DateEnd") = dateEnd.ToString("dd MMM yyyy")
                    drShift("TimeStart") = drShift2("TimeStart").ToString()
                    drShift("TimeEnd") = drShift2("TimeEnd").ToString()

                    If (drShift2("Confirm_Time").ToString() = "Y") Then
                        drShift("Confirm_Time") = "YES"
                    Else
                        drShift("Confirm_Time") = "NO"
                    End If

                    drShift("Remark") = drShift2("Remark").ToString()
                    drShift("Note") = drShift2("Note").ToString()

                    dtShift.Rows.Add(drShift)
                Next
            End If

            If (dtShift.Rows.Count > 0) Then
                gridWharf.DataSource = dtShift
                gridWharf.DataBind()
                PanelChangeEdit.Visible = True
            Else
                PanelChangeEdit.Visible = False
            End If
        Else
            PanelChangeEdit.Visible = False
        End If
    End Sub

    Protected Function CloneBookingShiftingSchema() As DataTable
        db = New DB_Class()
        db.queryString = "select TOP 1 * from Booking_Shifting"
        Dim dt As DataTable = db.getTable("bookingShift").Clone()
        dt.Columns.Add("Wharf", GetType(String))
        Return dt
    End Function
    Protected Sub gridWharf_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gridWharf.RowDataBound
        If (e.Row.RowType = DataControlRowType.DataRow) Then
            Dim ddlWharfTmp As DropDownList = CType(e.Row.FindControl("ddlWharf"), DropDownList)
            Dim port As String = ViewState("PORT").ToString()
            Dim dtAllWharf As DataTable = clsGet.Get_WharfAll(port)
            ddlWharfTmp.DataSource = dtAllWharf
            ddlWharfTmp.DataValueField = "BookingWharf"
            ddlWharfTmp.DataTextField = "Wharf"
            ddlWharfTmp.DataBind()
            Dim BookingWharf As String = gridWharf.DataKeys(e.Row.RowIndex)("BookingWharf").ToString()
            ddlWharfTmp.ClearSelection()
            ddlWharfTmp.Items.FindByValue(BookingWharf).Selected = True
            Dim Confirm_TimeStr As String = gridWharf.DataKeys(e.Row.RowIndex)("Confirm_Time").ToString()
            Dim btnScheduleConfirmTmp As Button = CType(e.Row.FindControl("btnScheduleConfirm"), Button)
            If (Confirm_TimeStr = "YES") Then
                btnScheduleConfirmTmp.Enabled = False
                btnScheduleConfirmTmp.CssClass = "ButtonStyle button-disable"
            End If

        End If
    End Sub
    Protected Sub gridWharf_RowCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gridWharf.RowCreated
        Dim c As Integer = gridWharf.Rows.Count
        If (e.Row.RowType = DataControlRowType.DataRow And e.Row.DataItemIndex > -1) Then
            db = New DB_Class()
            Dim bookingNo As String = ViewState("EditBooking").ToString()
            Dim productCell As TableCell = e.Row.Cells(3)
            Dim volumeCell As TableCell = e.Row.Cells(4)
            Dim Shifting_ID As String = gridWharf.DataKeys(e.Row.RowIndex)("Shifting_ID").ToString()
            Dim BookingWharf As String = gridWharf.DataKeys(e.Row.RowIndex)("BookingWharf").ToString()
            Dim products As New List(Of Product)
            If (Shifting_ID = "00000") Then
                db.queryString = "select * from BookingWharf_Product bwp left outer join Product p on bwp.Product_no=p.Product_no"
                db.queryString &= " where bwp.Booking_no='" & bookingNo & "' and bwp.BookingWharf='" & BookingWharf & "'"
                Dim dtBookingWharfPro As DataTable = db.getTable("bookingWharfPro")
                If (dtBookingWharfPro.Rows.Count > 0) Then
                    For Each drBookingWharfPro As DataRow In dtBookingWharfPro.Rows
                        Dim proNo As String = drBookingWharfPro("Product_no").ToString()
                        db.queryString = "select * from  Booking_Product where Booking_no='" & bookingNo & "' and Product_no='" & proNo & "'"
                        Dim productUnit As String = ""
                        Dim dtProductUnit As DataTable = db.getTable("proUnit")
                        If (dtProductUnit.Rows.Count > 0) Then
                            productUnit = " " & dtProductUnit.Rows(0)("Product_Unit").ToString()
                        End If
                        Dim product As New LiteralControl()
                        product.Text = drBookingWharfPro("Product_name").ToString() & "<br>"
                        productCell.Controls.Add(product)
                        Dim volLit As New LiteralControl()
                        volLit.Text = CDbl(drBookingWharfPro("Product_volume").ToString()).ToString("N", numberFormat) & productUnit & "<br>"
                        volumeCell.Controls.Add(volLit)
                    Next
                Else
                    db.queryString = "select * from  Booking_Product where Booking_no='" & bookingNo & "'"
                    Dim dtProduct As DataTable = db.getTable("Product")
                    If (dtProduct.Rows.Count > 0) Then
                        For Each drProduct As DataRow In dtProduct.Rows
                            Dim product As New LiteralControl()
                            product.Text = drProduct("Product_Name").ToString() & "<br>"
                            productCell.Controls.Add(product)
                            Dim volLit As New LiteralControl()
                            volLit.Text = CDbl(drProduct("Product_Amount").ToString()).ToString("N", numberFormat) _
                                        & " " & drProduct("Product_Unit").ToString() & "<br>"
                            volumeCell.Controls.Add(volLit)
                        Next
                    End If
                End If
            Else
                db.queryString = "select * from Booking_Shifting_Product bs left outer join Product p on bs.Product_no=p.Product_no" _
                            & " where Shifting_ID='" & Shifting_ID & "'"
                Dim dtShiftingProduct As DataTable = db.getTable("shiftingProduct")
                For Each drShiftingPro As DataRow In dtShiftingProduct.Rows
                    Dim proNo As String = drShiftingPro("Product_no").ToString()
                    db.queryString = "select * from  Booking_Product where Booking_no='" & bookingNo & "' and Product_no='" & proNo & "'"
                    Dim productUnit As String = ""
                    Dim dtProductUnit As DataTable = db.getTable("proUnit")
                    If (dtProductUnit.Rows.Count > 0) Then
                        productUnit = " " & dtProductUnit.Rows(0)("Product_Unit").ToString()
                    End If
                    Dim product As New LiteralControl()
                    product.Text = drShiftingPro("Product_name").ToString() & "<br>"
                    productCell.Controls.Add(product)
                    Dim volLit As New LiteralControl()
                    volLit.Text = CDbl(drShiftingPro("Product_volume").ToString()).ToString("N", numberFormat) & productUnit & "<br>"
                    volumeCell.Controls.Add(volLit)
                Next
            End If
        End If
    End Sub
    Private Sub gridWharf_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gridWharf.RowCommand
        db = New DB_Class()
        Dim bookingNo As String = ViewState("EditBooking").ToString()
        Dim c As Control = CType(e.CommandSource, Control)
        Dim gvr As GridViewRow = CType(c.NamingContainer, GridViewRow)
        Dim Shifting_ID As String = gridWharf.DataKeys(gvr.RowIndex)("Shifting_ID").ToString()
        Dim ddlWharfTmp As DropDownList = CType(gvr.FindControl("ddlWharf"), DropDownList)
        Dim oldWharf As String = gridWharf.DataKeys(gvr.RowIndex)("BookingWharf").ToString()

        Dim txtDateTmp As TextBox = CType(gvr.FindControl("txtDate"), TextBox)
        Dim dateStart As Date = Date.ParseExact(txtDateTmp.Text, "dd MMM yyyy", New CultureInfo("en-US"))
        Dim txtTimeBookingStartTmp As TextBox = CType(gvr.FindControl("txtTimeBookingStart"), TextBox)

        Dim txtDateToTmp As TextBox = CType(gvr.FindControl("txtDateTo"), TextBox)
        Dim dateEnd As Date = Date.ParseExact(txtDateToTmp.Text, "dd MMM yyyy", New CultureInfo("en-US"))
        Dim txtTimeBookingEndTmp As TextBox = CType(gvr.FindControl("txtTimeBookingEnd"), TextBox)

        Dim txtScheduleRemarkTmp As TextBox = CType(gvr.FindControl("txtScheduleRemark"), TextBox)
        Dim txtScheduleNoteTmp As TextBox = CType(gvr.FindControl("txtScheduleNote"), TextBox)
        Dim saveBookingWharf As String = String.Empty
        Dim saveBookingShifting As String = String.Empty

        db.queryString = "update BookingWharf set BookingWharf='{0}',Date_From='{1}',Date_To='{2}',DateStart='{3}',DateEnd='{4}'"
        db.queryString &= " ,TimeStart='{5}',TimeEnd='{6}',Remark='{7}',Note='{8}'"

        db.queryString = String.Format(db.queryString, ddlWharfTmp.SelectedValue, dateStart.ToString("dd MMM yyyy"), dateEnd.ToString("dd MMM yyyy") _
                           , dateStart.ToString("dd/MM/yyyy"), dateEnd.ToString("dd/MM/yyyy"), txtTimeBookingStartTmp.Text _
                           , txtTimeBookingEndTmp.Text, txtScheduleRemarkTmp.Text, txtScheduleNoteTmp.Text)
        saveBookingWharf = db.queryString & ",Confirm_Time='{0}'"


        db.queryString = "update Booking_Shifting set BookingWharf='{0}',DateStart='{1}',DateEnd='{2}',TimeStart='{3}',TimeEnd='{4}'"
        db.queryString &= ",Remark='{5}',Note='{6}'"
        db.queryString = String.Format(db.queryString, ddlWharfTmp.SelectedValue, dateStart.ToString("dd/MM/yyyy"), dateEnd.ToString("dd/MM/yyyy") _
                                       , txtTimeBookingStartTmp.Text, txtTimeBookingEndTmp.Text, txtScheduleRemarkTmp.Text, txtScheduleNoteTmp.Text)
        saveBookingShifting = db.queryString & ",Confirm_Time='{0}'"
        Dim btnScheduleConfirmTmp As Button = CType(gvr.FindControl("btnScheduleConfirm"), Button)
        If (e.CommandName = "cmdSave") Then
            If (Shifting_ID = "00000") Then

                db.queryString = String.Format(saveBookingWharf & " where Booking_no='" & bookingNo & "' and BookingWharf='" & oldWharf & "'", "N")


                If (db.insertUpdate() = "") Then
                    db.queryString = "update BookingWharf_Product set BookingWharf='{0}' where Booking_no='" & bookingNo & "' and BookingWharf='" & oldWharf & "'"
                    db.queryString = String.Format(db.queryString, ddlWharfTmp.SelectedValue)
                    db.insertUpdate()
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", String.Format("alert('{0}');", "บันทึกข้อมูลสำเร็จ"), True)
                    gvr.Cells(1).Text = "NO"
                    btnScheduleConfirmTmp.Enabled = True
                    btnScheduleConfirmTmp.CssClass = "ButtonStyle"
                Else
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", String.Format("alert('{0}');", "ไม่สามารถบันทึกข้อมูลได้"), True)
                End If
            Else

                db.queryString = String.Format(saveBookingShifting & " where Shifting_ID='" & Shifting_ID & "'", "N")

                If (db.insertUpdate() = "") Then
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", String.Format("alert('{0}');", "บันทึกข้อมูลสำเร็จ"), True)
                    gvr.Cells(1).Text = "NO"
                    btnScheduleConfirmTmp.Enabled = True
                    btnScheduleConfirmTmp.CssClass = "ButtonStyle"
                Else
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", String.Format("alert('{0}');", "ไม่สามารถบันทึกข้อมูลได้"), True)
                End If
            End If
            'If Not (Session("isFromSchedule") Is Nothing) Then
            '   ' Response.Redirect("frm_ManageBooking.aspx" & Request.Url.Query)
            'End If

            'ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", String.Format("alert('{0}');", gvr.RowIndex.ToString()), True)
        ElseIf (e.CommandName = "cmdConfirm") Then
            If (Shifting_ID = "00000") Then
                db.queryString = String.Format(saveBookingWharf & " where Booking_no='" & bookingNo & "' and BookingWharf='" & oldWharf & "'", "Y")
                'db.queryString = "update BookingWharf set Confirm_Time='Y' where Booking_no='" & bookingNo & "' and BookingWharf='" & oldWharf & "'"
                If (db.insertUpdate() = "") Then
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", String.Format("alert('{0}');", "บันทึกข้อมูลสำเร็จ"), True)
                    gvr.Cells(1).Text = "YES"
                    btnScheduleConfirmTmp.Enabled = False
                    btnScheduleConfirmTmp.CssClass = "ButtonStyle button-disable"
                Else
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", String.Format("alert('{0}');", "ไม่สามารถบันทึกข้อมูลได้"), True)
                End If
            Else
                'db.queryString = "update Booking_Shifting set Confirm_Time='Y' where Shifting_ID='" & Shifting_ID & "'"
                db.queryString = String.Format(saveBookingShifting & " where Shifting_ID='" & Shifting_ID & "'", "Y")
                If (db.insertUpdate() = "") Then
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", String.Format("alert('{0}');", "บันทึกข้อมูลสำเร็จ"), True)
                    gvr.Cells(1).Text = "YES"
                    btnScheduleConfirmTmp.Enabled = False
                    btnScheduleConfirmTmp.CssClass = "ButtonStyle button-disable"
                Else
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", String.Format("alert('{0}');", "ไม่สามารถบันทึกข้อมูลได้"), True)
                End If
            End If
            'If Not (Session("isFromSchedule") Is Nothing) Then
            '    Response.Redirect("frm_ManageBooking.aspx" & Request.Url.Query)
            'End If
        End If

    End Sub
    Private Sub gridItem_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gridItem.RowCommand
        Dim Index As Integer = Convert.ToInt32(e.CommandArgument)
        If (gridItem.PageIndex <> 0) Then
            Index = Index Mod (gridItem.PageIndex * 10)
        End If
        If e.CommandName = "Edit" Then
            EditBooking(gridItem.DataKeys(Index).Values("Booking_no"), "", "", gridItem.DataKeys(Index).Values("Marketing_approve") & "")
        ElseIf e.CommandName = "Detail" Then
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " document.getElementById('ctl00_contentplaceholder1_IframeDetailPopup').src = '../FormPopup/Detail_VesselBerth_Popup.aspx';", True)
            Session("Booking_no_Detail") = gridItem.DataKeys(Index).Values("Booking_no")
            ModalPopupExtender5.Show()
        End If
    End Sub
    Protected Sub btnManageShifting_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnManageShifting.Click
        Dim d As String = ViewState("EditBooking").ToString()
        Session("Shifting") = ViewState("EditBooking").ToString()
        Session("PORT") = ViewState("PORT").ToString()
        'Dim x As String = ViewState("PORT").ToString()
        ModalPopupShifting.Show()
    End Sub
    Protected Sub btnUpdateScheduleDummy_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpdateScheduleDummy.Click
        LoadShipSchedule()
    End Sub
    Public Sub Paginate(ByVal sender As Object, ByVal e As CommandEventArgs)
        If (Session("Role") & "" = "00003") Then
            ViewState("Booking_OLD") = ""
            Dim CurrentIndex As Integer = gridItemMarketing.PageIndex
            Select Case e.CommandArgument.ToString().ToLower()
                Case "first"
                    gridItemMarketing.PageIndex = 0
                Case "prev"
                    If (gridItemMarketing.PageIndex <> 0) Then
                        gridItemMarketing.PageIndex = CurrentIndex - 1
                    End If
                Case "next"
                    If (gridItemMarketing.PageIndex <> gridItemMarketing.PageCount) Then
                        gridItemMarketing.PageIndex = CurrentIndex + 1
                    End If
                Case "last"
                    gridItemMarketing.PageIndex = gridItemMarketing.PageCount
            End Select
            gridItemMarketing.DataSource = ViewState("Manage")
            gridItemMarketing.DataBind()
        Else
            Dim CurrentIndex As Integer = gridItem.PageIndex
            Select Case e.CommandArgument.ToString().ToLower()
                Case "first"
                    gridItem.PageIndex = 0
                Case "prev"
                    If (gridItem.PageIndex <> 0) Then
                        gridItem.PageIndex = CurrentIndex - 1
                    End If
                Case "next"
                    If (gridItem.PageIndex <> gridItem.PageCount) Then
                        gridItem.PageIndex = CurrentIndex + 1
                    End If
                Case "last"
                    gridItem.PageIndex = gridItem.PageCount
            End Select
            gridItem.DataSource = ViewState("Manage")
            gridItem.DataBind()
            LoadBOoking()
            Timer1_Tick(sender, e)
        End If

    End Sub

    Protected Sub ddlPage_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
        If (Session("Role") & "" = "00003") Then
            ViewState("Booking_OLD") = ""
            Dim Page As GridViewRow = gridItemMarketing.BottomPagerRow
            Dim ddlPage As DropDownList = CType(Page.Cells(0).FindControl("ddlPage"), DropDownList)
            gridItemMarketing.PageIndex = ddlPage.SelectedIndex
            gridItemMarketing.DataSource = ViewState("Manage")
            gridItemMarketing.DataBind()
        Else
            Dim Page As GridViewRow = gridItem.BottomPagerRow
            Dim ddlPage As DropDownList = CType(Page.Cells(0).FindControl("ddlPage"), DropDownList)
            gridItem.PageIndex = ddlPage.SelectedIndex
            gridItem.DataSource = ViewState("Manage")
            gridItem.DataBind()
            Timer1_Tick(sender, e)
        End If
    End Sub

    Private Sub gridItem_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gridItem.RowDataBound
        If (e.Row.RowType = DataControlRowType.DataRow) Then
            Dim imgVPS As Image = CType(e.Row.FindControl("imgVPS"), Image)
            Dim imgMRI As Image = CType(e.Row.FindControl("imgMRI"), Image)
            Dim imgVPSComment As Image = CType(e.Row.FindControl("imgVPSComment"), Image)
            Dim imgMRIComment As Image = CType(e.Row.FindControl("imgMRIComment"), Image)
            Dim imgMKT As Image = CType(e.Row.FindControl("imgMKT"), Image)
            Dim imgProduct As Image = CType(e.Row.FindControl("imgProduct"), Image)
            Dim imgCustom As Image = CType(e.Row.FindControl("imgCustom"), Image)
            Dim imgFinance As Image = CType(e.Row.FindControl("imgFinance"), Image)
            clsFc.GetImageStatus(imgVPS, imgMRI, imgMKT, gridItem.DataKeys(e.Row.RowIndex).Values("VPS_approve"), gridItem.DataKeys(e.Row.RowIndex).Values("MRI_approve"), gridItem.DataKeys(e.Row.RowIndex).Values("Marketing_approve"), gridItem.DataKeys(e.Row.RowIndex).Values("Status"))
            clsFc.GetImageStatusMKT(imgProduct, imgCustom, imgFinance, gridItem.DataKeys(e.Row.RowIndex).Values("MKT_Product"), gridItem.DataKeys(e.Row.RowIndex).Values("MKT_Custom"), gridItem.DataKeys(e.Row.RowIndex).Values("MKT_Finance"))
            'test_label.Text &= gridItem.DataKeys(e.Row.RowIndex).Values("Status") & "<br>"



            If (gridItem.DataKeys(e.Row.RowIndex).Values("Payin") & "" = "0") Then
                Dim dt As DataTable = clsGet.Get_Booking_Gl_Account(gridItem.DataKeys(e.Row.RowIndex).Values("Booking_no"), gridItem.DataKeys(e.Row.RowIndex).Values("MAgent_no"))
                If (dt.Rows.Count > 0) Then
                    imgMKT.ImageUrl = "~/Image/green.png"
                Else
                    imgMKT.ImageUrl = "~/Image/red.png"
                End If
            ElseIf (gridItem.DataKeys(e.Row.RowIndex).Values("Marketing_approve") & "" = "") Then
                imgMKT.ImageUrl = "~/Image/red.png"
            Else
                imgMKT.ImageUrl = "~/Image/green.png"
            End If
            Dim userRole As String = ""
            Try
                userRole = Session("Role").ToString()
            Catch ex As Exception
                Response.Redirect("~/Form/logon.aspx")
            End Try


            If userRole = "00005" Then
                If imgMRI.ImageUrl = "~/Image/green.png" Then
                    Dim chkBoxAppove As CheckBox = New CheckBox()
                    chkBoxAppove = CType(e.Row.FindControl("checkApprove"), CheckBox)
                    chkBoxAppove.Checked = True
                    chkBoxAppove.Enabled = False
                End If
            End If


            If (gridItem.DataKeys(e.Row.RowIndex).Values("Remark_VPS") & "" <> "") Then
                imgVPSComment.Visible = True
            Else
                imgVPSComment.Visible = False
            End If
            If (gridItem.DataKeys(e.Row.RowIndex).Values("Remark_MRI") & "" <> "") Then
                imgMRIComment.Visible = True
            Else
                imgMRIComment.Visible = False
            End If

            Dim imgConfrim As Image = CType(e.Row.FindControl("imgConfrim"), Image)
            If (gridItem.DataKeys(e.Row.RowIndex).Values("Confirm_Time") & "" = "Y") Then
                imgConfrim.ImageUrl = "~/Image/4558.png"
            Else
                imgConfrim.ImageUrl = "~/Image/4557.gif"
            End If

            Dim Status As String = ""
            Dim Tooltip As String = ""
            clsGet.GetStatus_Working(gridItem.DataKeys(e.Row.RowIndex).Values("Booking_no"), gridItem.DataKeys(e.Row.RowIndex).Values("PORT"), Status, Tooltip)
            e.Row.Cells(3).Text = Status
            e.Row.Cells(3).ToolTip = Tooltip

            If (gridItem.DataKeys(e.Row.RowIndex).Values("Date_From") & "" <> "") Then
                If (gridItem.DataKeys(e.Row.RowIndex).Values("Date_From") & "" = gridItem.DataKeys(e.Row.RowIndex).Values("Date_To") & "") Then
                    e.Row.Cells(4).Text = gridItem.DataKeys(e.Row.RowIndex).Values("Date_To")
                Else
                    e.Row.Cells(4).Text = gridItem.DataKeys(e.Row.RowIndex).Values("Date_From").ToString.Substring(0, 2) & "-" & gridItem.DataKeys(e.Row.RowIndex).Values("Date_To")
                End If

                e.Row.Cells(5).Text = gridItem.DataKeys(e.Row.RowIndex).Values("Booking_Date") & " : " & gridItem.DataKeys(e.Row.RowIndex).Values("Booking_Time")

                e.Row.Cells(6).Text = e.Row.Cells(6).Text & " hours"
                '----------'----------
                If (gridItem.DataKeys(e.Row.RowIndex).Values("Vehicle_Destination") & "" = "O") Then
                    If (gridItem.DataKeys(e.Row.RowIndex).Values("Vehicle_TypeBuy") & "" = "F") Then
                        e.Row.Cells(18).Text = "FOB" 'รูปแบบการซื้อขาย
                    ElseIf (gridItem.DataKeys(e.Row.RowIndex).Values("Vehicle_TypeBuy") & "" = "C") Then
                        e.Row.Cells(18).Text = "CFR"
                    ElseIf (gridItem.DataKeys(e.Row.RowIndex).Values("Vehicle_TypeBuy") & "" = "I") Then
                        e.Row.Cells(18).Text = "CIF"
                    Else
                        e.Row.Cells(18).Text = "อื่นๆ" 'รูปแบบการซื้อขาย
                    End If
                Else
                    e.Row.Cells(18).Text = "" 'รูปแบบการซื้อขาย
                    'e.Row.Cells(16).Text = ""
                End If
                If (gridItem.DataKeys(e.Row.RowIndex).Values("Demurrage_Money") & "" = "B") Then
                    If (gridItem.DataKeys(e.Row.RowIndex).Values("Demurrage") & "" = "") Then
                        e.Row.Cells(17).Text = "- BAHT"
                    Else
                        e.Row.Cells(17).Text = gridItem.DataKeys(e.Row.RowIndex).Values("Demurrage") & " BAHT"
                    End If
                ElseIf (gridItem.DataKeys(e.Row.RowIndex).Values("Demurrage_Money") & "" = "U") Then
                    If (gridItem.DataKeys(e.Row.RowIndex).Values("Demurrage") & "" = "") Then
                        e.Row.Cells(17).Text = "- USD"
                    Else
                        e.Row.Cells(17).Text = gridItem.DataKeys(e.Row.RowIndex).Values("Demurrage") & " USD"
                    End If
                End If
            End If

            Dim Product_Name As String = ""
            Dim Product_Amount As String = ""
            Dim Owner_name As String = ""
            Dim dtLog As DataTable
            dtLog = clsGet.Get_Booking_Product(gridItem.DataKeys(e.Row.RowIndex).Values("Booking_no"))
            For Each dr As DataRow In dtLog.Rows
                If (dr.Item("Product_name") & "" <> "") Then
                    Dim proAmount As Double = CDbl(dr("Product_Amount").ToString())
                    If (Product_Name <> "") Then
                        Product_Name &= "<br />" & dr.Item("Product_name") & ""
                        Product_Amount &= "<br />" & proAmount.ToString("N", numberFormat) & ""
                        Owner_name &= "<br />" & dr.Item("Owner_Product_Name") & ""
                    Else
                        Product_Name = dr.Item("Product_name") & ""
                        Product_Amount = proAmount.ToString("N", numberFormat)
                        Owner_name = dr.Item("Owner_Product_Name") & ""
                    End If
                End If
            Next
            If (gridItem.DataKeys(e.Row.RowIndex).Values("BunkerFO_Point") & "" <> "") And (gridItem.DataKeys(e.Row.RowIndex).Values("BunkerFO_Point") & "" <> "0") Then
                'BunkerFO 1 คัน,BunkerDO 1 คัน
                If Product_Name = "" Then
                    Product_Name = "BunkerFO"
                    Product_Amount = gridItem.DataKeys(e.Row.RowIndex).Values("BunkerFO_Point") & " คัน"
                Else
                    Product_Name &= "<br />" & "BunkerFO"
                    Product_Amount &= "<br />" & gridItem.DataKeys(e.Row.RowIndex).Values("BunkerFO_Point") & " คัน"
                End If
            End If
            If (gridItem.DataKeys(e.Row.RowIndex).Values("BunkerDO_Point") & "" <> "") And (gridItem.DataKeys(e.Row.RowIndex).Values("BunkerDO_Point") & "" <> "0") Then
                If Product_Name = "" Then
                    Product_Name = "BunkerDO"
                    Product_Amount = gridItem.DataKeys(e.Row.RowIndex).Values("BunkerDO_Point") & " คัน"
                Else
                    Product_Name &= "<br />" & "BunkerDO"
                    Product_Amount &= "<br />" & gridItem.DataKeys(e.Row.RowIndex).Values("BunkerDO_Point") & " คัน"
                End If
            End If
            Dim File_Upload As String = ""
            If (gridItem.DataKeys(e.Row.RowIndex).Values("File_Upload") & "" <> "") Then
                For i As Integer = 0 To gridItem.DataKeys(e.Row.RowIndex).Values("File_Upload").ToString.Split(",").Length - 1
                    If (gridItem.DataKeys(e.Row.RowIndex).Values("File_Upload").ToString.Split(",")(i) & "" <> "") Then
                        If File_Upload = "" Then
                            File_Upload = gridItem.DataKeys(e.Row.RowIndex).Values("File_Upload").ToString.Split(",")(i)
                        Else
                            File_Upload &= "<br />" & gridItem.DataKeys(e.Row.RowIndex).Values("File_Upload").ToString.Split(",")(i)
                        End If
                    End If
                Next
            End If

            Dim productCell As TableCell = e.Row.Cells(8)
            Dim productAmount As TableCell = e.Row.Cells(9)
            e.Row.Cells(7).Text = File_Upload
            'Dim productUnitCell As TableCell = e.Row.Cells(10)
            Dim productUtnitTmp As String = ""
            ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
            '''''''''''''''''''''''Modifing Product''''''''''''''''''''''''''
            ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
            Dim hrTag As String = "<hr style='height:1px;background-color:#000;color:#000;pdding:0;margin:0'/>"
            Dim productWharfCell As TableCell = e.Row.Cells(23)


            Dim bookingNo As String = gridItem.DataKeys(e.Row.RowIndex)("Booking_no").ToString()
            db.queryString = "select * from BookingWharf_Product bwp"
            db.queryString &= " left outer join Booking_Product bp on (bwp.Product_no=bp.Product_no and bp.Booking_no='" & bookingNo & "')"
            db.queryString &= " left outer join Wharf w on bwp.BookingWharf=w.BookingWharf"
            db.queryString &= " where bwp.Booking_no='" & bookingNo & "'"
            Dim dtBookingWharfProduct As DataTable = db.getTable("wharfPro")

            Dim productList As New List(Of Product)
            If (dtBookingWharfProduct.Rows.Count > 0) Then
                Product_Name = ""
                Product_Amount = ""
                'productUnitCell.Text = ""
                'productWharfCell.Text = dtBookingWharfProduct.Rows(0)("Wharf").ToString() & "<br>"

                For Each drWharfProduct As DataRow In dtBookingWharfProduct.Rows
                    Dim proAmount As Double = CDbl(drWharfProduct("Product_volume").ToString())
                    Product_Name &= drWharfProduct("Product_name").ToString() & "<br>"
                    ' productUnitCell.Text &= drWharfProduct("Product_Unit").ToString() & "<br>"
                    Product_Amount &= proAmount.ToString("N", numberFormat) & "<br>"
                    productUtnitTmp &= drWharfProduct("Product_Unit").ToString() & "<br>"
                Next
            End If
            Dim shiftingList As New List(Of Shifting)
            shiftingList = New Shifting().GetShifting(bookingNo)
            If (shiftingList.Count > 0) Then

                For Each shiftItem As Shifting In shiftingList
                    If (shiftItem.Product.Length > 0) Then

                        Product_Name &= hrTag
                        Product_Amount &= hrTag
                        productWharfCell.Text &= hrTag & shiftItem.WharfName & "<br>"
                        productUtnitTmp &= hrTag
                        ' productUnitCell.Text &= hrTag
                        For Each productItem As Product In shiftItem.Product
                            Product_Name &= productItem.ProductName & "<br>"
                            Dim proVol As Double = CDbl(productItem.ProductVolume)
                            Product_Amount &= proVol.ToString("N", numberFormat) & "<br>"
                            productUtnitTmp &= productItem.ProductUnit & "<br>"
                        Next
                    End If
                Next
            End If
            productCell.Text = Product_Name
            productAmount.Text = Product_Amount
            '  productWharfCell.Text = wharfTmp
            '----------------
            Dim Unit() As String = (gridItem.DataKeys(e.Row.RowIndex).Values("Product_Unit") & "").ToString.Split(",")
            Dim Text As String = ""
            For i As Integer = 0 To Unit.Length - 1
                If (Unit(i) & "" <> "") Then
                    If (Text = "") Then
                        Text = Unit(i)
                    Else
                        Text &= "<br />" & Unit(i)
                    End If
                End If
            Next
            If (productUtnitTmp <> "") Then
                Text = productUtnitTmp
            End If
            e.Row.Cells(10).Text = Text
            Text = ""
            Unit = (gridItem.DataKeys(e.Row.RowIndex).Values("BUYER") & "").ToString.Split(",")
            For i As Integer = 0 To Unit.Length - 1
                If (Unit(i) & "" <> "") Then
                    If (Text = "") Then
                        Text = Unit(i)
                    Else
                        Text &= "<br />" & Unit(i)
                    End If
                End If
            Next
           
            e.Row.Cells(11).Text = Text
            '---------------
            Text = ""
            Unit = (gridItem.DataKeys(e.Row.RowIndex).Values("SELLER") & "").ToString.Split(",")
            For i As Integer = 0 To Unit.Length - 1
                If (Unit(i) & "" <> "") Then
                    If (Text = "") Then
                        Text = Unit(i)
                    Else
                        Text &= "<br />" & Unit(i)
                    End If
                End If
            Next
            e.Row.Cells(12).Text = Text '<<<<<<<
            If (clsFc.GetStatusCancel(gridItem.DataKeys(e.Row.RowIndex).Values("Status"))) Then
                e.Row.BackColor = Drawing.Color.Red
            Else
                Dim Product_Event As String = clsGet.Get_ProductEvent(gridItem.DataKeys(e.Row.RowIndex).Values("Booking_no"))
                If (Product_Event = "L") Then
                    If (gridItem.DataKeys(e.Row.RowIndex).Values("Vehicle_Destination") & "" = "O") Then
                        e.Row.BackColor = Drawing.Color.FromName("#6698FF")
                    Else
                        e.Row.BackColor = Drawing.Color.FromName("#A0CFEC")
                    End If
                    If (gridItem.DataKeys(e.Row.RowIndex).Values("PORT") & "" = "B") Then
                        e.Row.Cells(12).Text = Owner_name
                        '-------
                    End If
                ElseIf (Product_Event = "D") Then
                    If (gridItem.DataKeys(e.Row.RowIndex).Values("Vehicle_Destination") & "" = "O") Then
                        e.Row.BackColor = Drawing.Color.FromName("#347C17")
                    Else
                        e.Row.BackColor = Drawing.Color.FromName("#52D017")
                    End If
                    If (gridItem.DataKeys(e.Row.RowIndex).Values("PORT") & "" = "B") Then
                        'e.Row.Cells(10).Text = Owner_name
                    End If
                Else
                    e.Row.BackColor = Drawing.Color.White
                End If
            End If
        ElseIf (e.Row.RowType = DataControlRowType.Pager) Then
            Dim Page As GridViewRow = gridItem.BottomPagerRow
            Dim ddlPage As DropDownList = CType(e.Row.FindControl("ddlPage"), DropDownList)
            Dim lblPageCount As Label = CType(e.Row.FindControl("lbPageCount"), Label)
            If Not (ddlPage Is Nothing) Then
                For i As Integer = 0 To gridItem.PageCount - 1
                    Dim intPageNumber As Integer = i + 1
                    Dim IsItem As New ListItem(intPageNumber.ToString())
                    If (i = gridItem.PageIndex) Then
                        IsItem.Selected = True
                    End If
                    ddlPage.Items.Add(IsItem)
                Next
            End If
            If Not (lblPageCount Is Nothing) Then
                lblPageCount.Text = gridItem.PageCount.ToString()
            End If
        ElseIf (e.Row.RowType = DataControlRowType.Header) Then
            gridItem.Columns(1).SortExpression = "LAYCAN"
        End If
    End Sub

    Private Sub gridItem_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles gridItem.RowEditing

    End Sub

    Protected Sub btnsave_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnsave.Click
        If (ddlStatus.SelectedValue = "ยังไม่ได้เริ่มดำเนินการ") Then
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการระบุสถานะ!!');", True)
            Exit Sub
        End If
        UpdateStatus(ddlStatus.SelectedValue)
    End Sub

    Private Sub btnapprove_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnapprove.Click
        If (Session("Role") & "" = "00004") Then
            'VPS
            UpdateStatus("VA")
        ElseIf (Session("Role") & "" = "00005") Then
            'MRI
            If (rowVehicle.Visible) Then
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการ Update ข้อมูลเรือก่อนทำการอนุมัติ !!');", True)
            Else
                Dim dtBooking As DataTable = clsGet.Get_BookingOneRecord(ViewState("EditBooking")).Tables(0)
                If (dtBooking.Rows(0).Item("Marketing_approve") & "" = "") Then
                    UpdateStatus("MA")
                Else
                    UpdateStatus("MO")
                End If

            End If
        End If
    End Sub
    Private Sub UpdateStatus(ByVal Status As String)
        Dim conn As New System.Data.SqlClient.SqlConnection(connString)
        Dim clsDB As New ClassDatabase
        Dim condition As Boolean = True
        Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
        Dim ds_Log As DataTable = clsGet.Get_Booking_LOG(ViewState("EditBooking"))
        Dim dsBooking As DataTable = clsGet.Get_BookingOneRecord(ViewState("EditBooking")).Tables(0)
        Dim Vps As String = CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("User_name") & " " & DateTime.Now.ToString("yyyyMMdd:HHmmss")
        Dim OldStatus As String = ds_Log.Rows(0).Item("Status") & ""
        Dim ChkOwner As Boolean = False
        Dim s As String = "xx"
        Try
            s = ViewState("Owner").ToString()

            If (ViewState("Owner") <> dsBooking.Rows(0).Item("MAgent_No")) Then
                If (clsGet.Get_Bill_TO_Bulk(ViewState("EditBooking") & "", ViewState("Owner") & "") <> "0") Then
                    ChkOwner = True
                End If
            End If
        Catch ex As Exception

        End Try

        Dim Shifting As String = ""
        s = s
        Application.Lock()
        conn.Open()

        Dim Booking_Log As String = Date.Now.ToString("yyyyMMddHHmmss")
        tran = clsDB.BeginTran(conn)
        Try
            If (Session("Role") & "" = "00004") Then 'VPS
                If (clsFc.UpdateVPSBooking(ViewState("EditBooking"), txtRemark.Text, Vps, Status, "", "", ds_Log.Rows(0).Item("Marketing_approve") & "", "", ds_Log.Rows(0).Item("Bill_To_no"), ds_Log.Rows(0).Item("Bill_To_name"), Shifting, conn, tran) > 0) Then
                    If (clsFc.InsertBooking_Log(Booking_Log, ViewState("EditBooking"), ds_Log.Rows(0).Item("Booking_Code"), ds_Log.Rows(0).Item("Booking_name"), ds_Log.Rows(0).Item("Vehicle_no"), ds_Log.Rows(0).Item("Vehicle_Text"), ds_Log.Rows(0).Item("Vehicle_LOA"), ds_Log.Rows(0).Item("Vehicle_DWT"), ds_Log.Rows(0).Item("Vehicle_Draft"), ds_Log.Rows(0).Item("Vehicle_GRT"), ds_Log.Rows(0).Item("Date_From"), ds_Log.Rows(0).Item("Date_To"), ds_Log.Rows(0).Item("PORT"), ds_Log.Rows(0).Item("Vehicle_destination"), ds_Log.Rows(0).Item("Vehicle_TypeBuy"), ds_Log.Rows(0).Item("Remark"), Status, txtRemark.Text, Vps, ds_Log.Rows(0).Item("Remark_MRI") & "", ds_Log.Rows(0).Item("MRI_approve") & "", ds_Log.Rows(0).Item("Marketing_approve") & "", ds_Log.Rows(0).Item("Product_name"), ds_Log.Rows(0).Item("Product_Amount"), ds_Log.Rows(0).Item("MAgent_no"), ds_Log.Rows(0).Item("MAgent_name"), ds_Log.Rows(0).Item("SAgent_no"), ds_Log.Rows(0).Item("SAgent_name"), ds_Log.Rows(0).Item("Booking_Date"), ds_Log.Rows(0).Item("Booking_Time"), ds_Log.Rows(0).Item("Buyer"), ds_Log.Rows(0).Item("Seller"), ds_Log.Rows(0).Item("Product_Unit"), ds_Log.Rows(0).Item("File_Upload"), ds_Log.Rows(0).Item("Vehicle_CNTRY"), ds_Log.Rows(0).Item("Lay_Time"), ds_Log.Rows(0).Item("MKT_Product"), ds_Log.Rows(0).Item("MKT_Custom"), ds_Log.Rows(0).Item("MKT_Finance"), ds_Log.Rows(0).Item("BunkerFO_chk"), ds_Log.Rows(0).Item("BunkerDO_chk"), ds_Log.Rows(0).Item("BunkerFO_Point"), ds_Log.Rows(0).Item("BunkerDO_Point"), ds_Log.Rows(0).Item("BunkerDetail"), ds_Log.Rows(0).Item("Water_Point"), ds_Log.Rows(0).Item("MKT_Approve"), ds_Log.Rows(0).Item("Cancel_By"), ds_Log.Rows(0).Item("Cancel_Description"), ds_Log.Rows(0).Item("Vps_Acknowledge"), ds_Log.Rows(0).Item("MKT_Acknowledge"), ds_Log.Rows(0).Item("Payin"), ds_Log.Rows(0).Item("Bill_To_no"), ds_Log.Rows(0).Item("Bill_To_name"), ds_Log.Rows(0).Item("StandardTime"), ds_Log.Rows(0).Item("Credit_Limit"), ds_Log.Rows(0).Item("Status_Pay"), ds_Log.Rows(0).Item("Demurrage"), ds_Log.Rows(0).Item("Demurrage_Money"), ds_Log.Rows(0).Item("Electricity") & "", Shifting, conn, tran) < 1) Then
                        condition = False
                    End If
                Else
                    condition = False
                End If
            ElseIf (Session("Role") & "" = "00005") Then 'MRI
                If (clsFc.UpdateVPSBooking(ViewState("EditBooking"), ds_Log.Rows(0).Item("Remark_VPS"), ds_Log.Rows(0).Item("VPS_approve"), Status, txtRemark.Text, Vps, ds_Log.Rows(0).Item("Marketing_approve") & "", "", ds_Log.Rows(0).Item("Bill_To_no"), ds_Log.Rows(0).Item("Bill_To_name"), Shifting, conn, tran) > 0) Then
                    If (clsFc.InsertBooking_Log(Booking_Log, ViewState("EditBooking"), ds_Log.Rows(0).Item("Booking_Code"), ds_Log.Rows(0).Item("Booking_name"), ds_Log.Rows(0).Item("Vehicle_no"), ds_Log.Rows(0).Item("Vehicle_Text"), ds_Log.Rows(0).Item("Vehicle_LOA"), ds_Log.Rows(0).Item("Vehicle_DWT"), ds_Log.Rows(0).Item("Vehicle_Draft"), ds_Log.Rows(0).Item("Vehicle_GRT"), ds_Log.Rows(0).Item("Date_From"), ds_Log.Rows(0).Item("Date_To"), ds_Log.Rows(0).Item("PORT"), ds_Log.Rows(0).Item("Vehicle_destination"), ds_Log.Rows(0).Item("Vehicle_TypeBuy"), ds_Log.Rows(0).Item("Remark"), Status, ds_Log.Rows(0).Item("Remark_VPS"), ds_Log.Rows(0).Item("VPS_approve"), txtRemark.Text, Vps, ds_Log.Rows(0).Item("Marketing_approve") & "", ds_Log.Rows(0).Item("Product_name"), ds_Log.Rows(0).Item("Product_Amount"), ds_Log.Rows(0).Item("MAgent_no"), ds_Log.Rows(0).Item("MAgent_name"), ds_Log.Rows(0).Item("SAgent_no"), ds_Log.Rows(0).Item("SAgent_name"), ds_Log.Rows(0).Item("Booking_Date"), ds_Log.Rows(0).Item("Booking_Time"), ds_Log.Rows(0).Item("Buyer"), ds_Log.Rows(0).Item("Seller"), ds_Log.Rows(0).Item("Product_Unit"), ds_Log.Rows(0).Item("File_Upload"), ds_Log.Rows(0).Item("Vehicle_CNTRY"), ds_Log.Rows(0).Item("Lay_Time"), ds_Log.Rows(0).Item("MKT_Product"), ds_Log.Rows(0).Item("MKT_Custom"), ds_Log.Rows(0).Item("MKT_Finance"), ds_Log.Rows(0).Item("BunkerFO_chk"), ds_Log.Rows(0).Item("BunkerDO_chk"), ds_Log.Rows(0).Item("BunkerFO_Point"), ds_Log.Rows(0).Item("BunkerDO_Point"), ds_Log.Rows(0).Item("BunkerDetail"), ds_Log.Rows(0).Item("Water_Point"), ds_Log.Rows(0).Item("MKT_Approve"), ds_Log.Rows(0).Item("Cancel_By"), ds_Log.Rows(0).Item("Cancel_Description"), ds_Log.Rows(0).Item("Vps_Acknowledge"), ds_Log.Rows(0).Item("MKT_Acknowledge"), ds_Log.Rows(0).Item("Payin"), ds_Log.Rows(0).Item("Bill_To_no"), ds_Log.Rows(0).Item("Bill_To_name"), ds_Log.Rows(0).Item("StandardTime"), ds_Log.Rows(0).Item("Credit_Limit"), ds_Log.Rows(0).Item("Status_Pay"), ds_Log.Rows(0).Item("Demurrage"), ds_Log.Rows(0).Item("Demurrage_Money"), ds_Log.Rows(0).Item("Electricity") & "", Shifting, conn, tran) < 1) Then
                        condition = False
                    End If
                Else
                    condition = False
                End If
            ElseIf (Session("Role") & "" = "00003") Then 'Marketing
                Dim Bill_To_no As String = ""
                Dim Bill_To_name As String = ""
                If (txtBillTo.Text.Trim() <> "") Then
                    Bill_To_no = txtBillTo.Text.Split("-")(0)
                    Bill_To_name = txtBillTo.Text.Split("-")(1)
                End If
                ViewState("bill_to") = Bill_To_no & "$" & Bill_To_name
                Dim dsMat As DataSet = Session("MAT_USE")
                If (ViewState("PORT") = "L") Then
                    If (clsFc.UpdateVPSBooking(ViewState("EditBooking"), ds_Log.Rows(0).Item("Remark_VPS"), ds_Log.Rows(0).Item("VPS_approve"), Status, ds_Log.Rows(0).Item("Remark_MRI"), ds_Log.Rows(0).Item("MRI_approve"), Vps, radioPayin.SelectedValue, Bill_To_no, Bill_To_name, Shifting, conn, tran) > 0) Then
                        If (clsFc.InsertBooking_Log(Booking_Log, ViewState("EditBooking"), ds_Log.Rows(0).Item("Booking_Code"), ds_Log.Rows(0).Item("Booking_name"), ds_Log.Rows(0).Item("Vehicle_no"), ds_Log.Rows(0).Item("Vehicle_Text"), ds_Log.Rows(0).Item("Vehicle_LOA"), ds_Log.Rows(0).Item("Vehicle_DWT"), ds_Log.Rows(0).Item("Vehicle_Draft"), ds_Log.Rows(0).Item("Vehicle_GRT"), ds_Log.Rows(0).Item("Date_From"), ds_Log.Rows(0).Item("Date_To"), ds_Log.Rows(0).Item("PORT"), ds_Log.Rows(0).Item("Vehicle_destination"), ds_Log.Rows(0).Item("Vehicle_TypeBuy"), ds_Log.Rows(0).Item("Remark"), Status, ds_Log.Rows(0).Item("Remark_VPS") & "", ds_Log.Rows(0).Item("VPS_approve") & "", ds_Log.Rows(0).Item("Remark_MRI") & "", ds_Log.Rows(0).Item("MRI_approve") & "", Vps, ds_Log.Rows(0).Item("Product_name"), ds_Log.Rows(0).Item("Product_Amount"), ds_Log.Rows(0).Item("MAgent_no"), ds_Log.Rows(0).Item("MAgent_name"), ds_Log.Rows(0).Item("SAgent_no"), ds_Log.Rows(0).Item("SAgent_name"), ds_Log.Rows(0).Item("Booking_Date"), ds_Log.Rows(0).Item("Booking_Time"), ds_Log.Rows(0).Item("Buyer"), ds_Log.Rows(0).Item("Seller"), ds_Log.Rows(0).Item("Product_Unit"), ds_Log.Rows(0).Item("File_Upload"), ds_Log.Rows(0).Item("Vehicle_CNTRY"), ds_Log.Rows(0).Item("Lay_Time"), ds_Log.Rows(0).Item("MKT_Product"), ds_Log.Rows(0).Item("MKT_Custom"), ds_Log.Rows(0).Item("MKT_Finance"), ds_Log.Rows(0).Item("BunkerFO_chk"), ds_Log.Rows(0).Item("BunkerDO_chk"), ds_Log.Rows(0).Item("BunkerFO_Point"), ds_Log.Rows(0).Item("BunkerDO_Point"), ds_Log.Rows(0).Item("BunkerDetail"), ds_Log.Rows(0).Item("Water_Point"), ds_Log.Rows(0).Item("MKT_Approve"), ds_Log.Rows(0).Item("Cancel_By"), ds_Log.Rows(0).Item("Cancel_Description"), ds_Log.Rows(0).Item("Vps_Acknowledge"), ds_Log.Rows(0).Item("MKT_Acknowledge"), ds_Log.Rows(0).Item("Payin"), ds_Log.Rows(0).Item("Bill_To_no"), ds_Log.Rows(0).Item("Bill_To_name"), ds_Log.Rows(0).Item("StandardTime"), ds_Log.Rows(0).Item("Credit_Limit"), ds_Log.Rows(0).Item("Status_Pay"), ds_Log.Rows(0).Item("Demurrage"), ds_Log.Rows(0).Item("Demurrage_Money"), ds_Log.Rows(0).Item("Electricity") & "", Shifting, conn, tran) < 1) Then
                            condition = False
                        End If
                    End If
                    clsFc.DeleteBookingTariff(ViewState("EditBooking"), "", conn, tran)
                    For Each dr As DataRow In dsMat.Tables(0).Rows
                        If (clsFc.InsertBookingTariff(dr.Item("MATERIAL"), ViewState("EditBooking"), dr.Item("Text_line"), dr.Item("Unit"), dr.Item("Count"), dr.Item("MAT_Default"), dr.Item("KBETR"), dr.Item("KONWA"), dr.Item("MAT_Relation"), dr.Item("MAT_ComputeM"), "N", "", Session("SumTotal") & "", conn, tran) > 0) Then
                            If (clsFc.InsertBookingTariff_Log(Booking_Log, dr.Item("MATERIAL"), ViewState("EditBooking"), dr.Item("Text_line"), dr.Item("Unit"), dr.Item("Count"), dr.Item("MAT_Default"), dr.Item("KBETR"), dr.Item("KONWA"), dr.Item("MAT_Relation"), dr.Item("MAT_ComputeM"), "N", "", conn, tran) < 1) Then
                                condition = False
                                Exit For
                            End If
                        Else
                            condition = False
                            Exit For
                        End If
                    Next
                Else
                    clsFc.DeleteBookingTariff(ViewState("EditBooking"), ViewState("Owner"), conn, tran)
                    'Agent
                    Try

                        For Each dr As DataRow In dsMat.Tables(0).Rows
                            If (clsFc.InsertBookingTariff(dr.Item("MATERIAL"), ViewState("EditBooking"), dr.Item("Text_line"), dr.Item("Unit"), dr.Item("Count"), dr.Item("MAT_Default"), dr.Item("KBETR"), dr.Item("KONWA"), dr.Item("MAT_Relation"), dr.Item("MAT_ComputeM"), "N", ViewState("Owner"), Session("SumTotal") & "", conn, tran) > 0) Then
                                If (clsFc.InsertBookingTariff_Log(Booking_Log, dr.Item("MATERIAL"), ViewState("EditBooking"), dr.Item("Text_line"), dr.Item("Unit"), dr.Item("Count"), dr.Item("MAT_Default"), dr.Item("KBETR"), dr.Item("KONWA"), dr.Item("MAT_Relation"), dr.Item("MAT_ComputeM"), "N", ViewState("Owner"), conn, tran) < 1) Then
                                    condition = False
                                    Exit For
                                End If
                            Else
                                condition = False
                                Exit For
                            End If
                        Next
                        If (dsBooking.Rows(0).Item("MAgent_no") & "" <> ViewState("Owner") & "") Or (ChkOwner) Then
                            'Owner
                            If (clsFc.UpdateTariffOwner(ViewState("EditBooking"), ViewState("Owner"), radioPayin.SelectedValue, Bill_To_no, Bill_To_name, Status, conn, tran) < 1) Then
                                condition = False
                            End If
                            'If (clsFc.UpdateBookingProduct_Status(ViewState("EditBooking"), ViewState("Owner") & "", "MO", conn, tran) < 1) Then
                            '    condition = False
                            'End If
                        Else
                            If (clsFc.UpdateVPSBooking(ViewState("EditBooking"), ds_Log.Rows(0).Item("Remark_VPS"), ds_Log.Rows(0).Item("VPS_approve"), Status, ds_Log.Rows(0).Item("Remark_MRI"), ds_Log.Rows(0).Item("MRI_approve"), Vps, radioPayin.SelectedValue, Bill_To_no, Bill_To_name, Shifting, conn, tran) > 0) Then
                                If (clsFc.InsertBooking_Log(Booking_Log, ViewState("EditBooking"), ds_Log.Rows(0).Item("Booking_Code"), ds_Log.Rows(0).Item("Booking_name"), ds_Log.Rows(0).Item("Vehicle_no"), ds_Log.Rows(0).Item("Vehicle_Text"), ds_Log.Rows(0).Item("Vehicle_LOA"), ds_Log.Rows(0).Item("Vehicle_DWT"), ds_Log.Rows(0).Item("Vehicle_Draft"), ds_Log.Rows(0).Item("Vehicle_GRT"), ds_Log.Rows(0).Item("Date_From"), ds_Log.Rows(0).Item("Date_To"), ds_Log.Rows(0).Item("PORT"), ds_Log.Rows(0).Item("Vehicle_destination"), ds_Log.Rows(0).Item("Vehicle_TypeBuy"), ds_Log.Rows(0).Item("Remark"), Status, ds_Log.Rows(0).Item("Remark_VPS") & "", ds_Log.Rows(0).Item("VPS_approve") & "", ds_Log.Rows(0).Item("Remark_MRI") & "", ds_Log.Rows(0).Item("MRI_approve"), Vps, ds_Log.Rows(0).Item("Product_name"), ds_Log.Rows(0).Item("Product_Amount"), ds_Log.Rows(0).Item("MAgent_no"), ds_Log.Rows(0).Item("MAgent_name"), ds_Log.Rows(0).Item("SAgent_no"), ds_Log.Rows(0).Item("SAgent_name"), ds_Log.Rows(0).Item("Booking_Date"), ds_Log.Rows(0).Item("Booking_Time"), ds_Log.Rows(0).Item("Buyer"), ds_Log.Rows(0).Item("Seller"), ds_Log.Rows(0).Item("Product_Unit"), ds_Log.Rows(0).Item("File_Upload"), ds_Log.Rows(0).Item("Vehicle_CNTRY"), ds_Log.Rows(0).Item("Lay_Time"), ds_Log.Rows(0).Item("MKT_Product"), ds_Log.Rows(0).Item("MKT_Custom"), ds_Log.Rows(0).Item("MKT_Finance"), ds_Log.Rows(0).Item("BunkerFO_chk"), ds_Log.Rows(0).Item("BunkerDO_chk"), ds_Log.Rows(0).Item("BunkerFO_Point"), ds_Log.Rows(0).Item("BunkerDO_Point"), ds_Log.Rows(0).Item("BunkerDetail"), ds_Log.Rows(0).Item("Water_Point"), ds_Log.Rows(0).Item("MKT_Approve"), ds_Log.Rows(0).Item("Cancel_By"), ds_Log.Rows(0).Item("Cancel_Description"), ds_Log.Rows(0).Item("Vps_Acknowledge"), ds_Log.Rows(0).Item("MKT_Acknowledge"), ds_Log.Rows(0).Item("Payin"), ds_Log.Rows(0).Item("Bill_To_no"), ds_Log.Rows(0).Item("Bill_To_name"), ds_Log.Rows(0).Item("StandardTime"), ds_Log.Rows(0).Item("Credit_Limit"), ds_Log.Rows(0).Item("Status_Pay"), ds_Log.Rows(0).Item("Demurrage"), ds_Log.Rows(0).Item("Demurrage_Money"), ds_Log.Rows(0).Item("Electricity") & "", Shifting, conn, tran) < 1) Then
                                    condition = False
                                End If
                            End If
                            'If (clsFc.UpdateBookingStatusOneField(ViewState("EditBooking"), "MO", conn, tran) < 1) Then
                            '    condition = False
                            'End If
                        End If
                    Catch ex As Exception
                        For Each dr As DataRow In dsMat.Tables(0).Rows
                            If (clsFc.InsertBookingTariff(dr.Item("MATERIAL"), ViewState("EditBooking"), dr.Item("Text_line"), dr.Item("Unit"), dr.Item("Count"), dr.Item("MAT_Default"), dr.Item("KBETR"), dr.Item("KONWA"), dr.Item("MAT_Relation"), dr.Item("MAT_ComputeM"), "N", "", Session("SumTotal") & "", conn, tran) > 0) Then
                                If (clsFc.InsertBookingTariff_Log(Booking_Log, dr.Item("MATERIAL"), ViewState("EditBooking"), dr.Item("Text_line"), dr.Item("Unit"), dr.Item("Count"), dr.Item("MAT_Default"), dr.Item("KBETR"), dr.Item("KONWA"), dr.Item("MAT_Relation"), dr.Item("MAT_ComputeM"), "N", "", conn, tran) < 1) Then
                                    condition = False
                                    Exit For
                                End If
                            Else
                                condition = False
                                Exit For
                            End If
                        Next
                    End Try
                End If
                'For Each dtMat As DataTable In dsMat.Tables


                'Next
                clsFc.UPDateMarketing_Approve(ViewState("EditBooking"), Vps, conn, tran)
                If (clsFc.UpdateTariffFree(Session("CodeMATFree_SAP"), ViewState("EditBooking"), ViewState("Owner") & "", conn, tran) > -1) Then
                    If (clsFc.UpdateTariffFree_LOG(Session("CodeMATFree_SAP"), ViewState("EditBooking"), Booking_Log, conn, tran) < 0) Then
                        condition = False
                    End If
                Else
                    condition = False
                End If

                'Insert Temp Estimate For Create Sale ORDER
                Dim dsMat_SAP As DataSet = Session("dsMat_SAP")
                Dim i_CountTable As Integer = -1
                ' clsFc.DeleteSAP_Temp_Estimate(ViewState("EditBooking"), ViewState("Owner") & "", conn, tran)
                If (ViewState("PORT") = "L") Then
                    clsFc.DeleteSAP_Temp_Estimate(ViewState("EditBooking"), "", "", conn, tran)
                Else
                    clsFc.DeleteSAP_Temp_Estimate(ViewState("EditBooking"), ViewState("Owner"), "", conn, tran)
                End If
                For Each dt As DataTable In dsMat_SAP.Tables
                    i_CountTable = i_CountTable + 1
                    For Each dm As DataRow In dt.Rows
                        Dim Owner_Product As String = Session("Customer_SAP") & ""
                        If Owner_Product = "" Then
                            Owner_Product = txtid.Text.Trim.Split("-")(0)
                        Else
                            Owner_Product = Owner_Product.Split("$")(i_CountTable)
                            If (Owner_Product = "") Then
                                Owner_Product = txtid.Text.Trim.Split("-")(0)
                            End If
                        End If
                        If (ViewState("PORT") = "B") Then
                            clsFc.DeleteSAP_Temp_Estimate(ViewState("EditBooking"), Owner_Product, dm.Item("id"), conn, tran)
                        End If

                        If (clsFc.InsertSAP_Temp_Estimate(ViewState("EditBooking"), dm.Item("id"), dm.Item("MAT_Name"), dm.Item("name"), dm.Item("data1").ToString().Replace(",", ""), dm.Item("data2").ToString().Replace(",", ""), dm.Item("data3").ToString().Replace(",", ""), dm.Item("data4").ToString().Replace(",", ""), Owner_Product, conn, tran) < 1) Then
                            condition = False
                            Exit For
                        End If
                    Next
                Next
                'If (condition) Then
                '    'ทำการบันทึก Log ด้วย
                '    If (radioPayin.SelectedValue = "1") Then
                '        Create_Credit_Sale(ViewState("EditBooking"), Vps, Status, Bill_To_no, Bill_To_name, condition)
                '    End If

                'End If
            End If

            If (condition) Then
                If clsDB.CommitTran(tran) Then
                    LoadBOoking()
                    Dim str As String = ""
                    Dim Action As String = ""
                    If (Session("Role") & "" = "00003") Then
                        Action = "MARKETING"
                        If (Status = "MO") Then
                            str = GenBody("รายการจองได้รับการอนุมัติ จากฝ่าย PTMP,PTMI และได้รับการยืนยันค่าประมาณการแล้ว กรุณาทำการตรวจสอบข้อมูลก่อนนำเรือเข้าสู่ท่าเรือ", ViewState("EditBooking"), ds_Log.Rows(0).Item("MAgent_no") & "-" & ds_Log.Rows(0).Item("MAgent_name"), ds_Log.Rows(0).Item("Vehicle_no") & "-" & ds_Log.Rows(0).Item("Vehicle_Text"), ds_Log.Rows(0).Item("Date_From") & "-" & ds_Log.Rows(0).Item("Date_To"))
                        Else
                            str = GenBody("รายการจองได้ถูกทำการ Confirm ค่าประการแล้วสามารถทำการตรวจสอบได้ผ่านระบบ iPORT", ViewState("EditBooking"), ds_Log.Rows(0).Item("MAgent_no") & "-" & ds_Log.Rows(0).Item("MAgent_name"), ds_Log.Rows(0).Item("Vehicle_no") & "-" & ds_Log.Rows(0).Item("Vehicle_Text"), ds_Log.Rows(0).Item("Date_From") & "-" & ds_Log.Rows(0).Item("Date_To"))
                        End If

                        If (radioPayin.SelectedValue = "1") Then
                            If (OldStatus <> "MO") Then
                                'Dim chkedit As Boolean = Create_Credit_Sale(ViewState("EditBooking"), Vps, Status, ViewState("bill_to").ToString().Split("$")(0), ViewState("bill_to").ToString().Split("$")(1), condition)
                                If (condition) Then
                                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ทำการ Confirm ค่าประมาณการเรียบร้อย !! ');", True)
                                    'If (chkedit) Then
                                    '    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ทำการสร้าง  Sale Order เรียบร้อย ');", True)
                                    'Else
                                    '    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('Document cannot be billed due to credit limit check ');", True)
                                    'End If
                                Else
                                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการบันทึกลง SAP');", True)
                                End If
                            Else
                                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('บันทึกข้อมูลสำเร็จ');", True)
                            End If

                        Else
                            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('บันทึกข้อมูลสำเร็จ');", True)
                        End If
                    Else
                        If (Session("Role") & "" = "00004") Then
                            Action = "VPS"
                            str = GenBody("รายการจองได้รับการอนุมัติจากฝ่าย PTMP รอการอนุมัติจากฝ่าย PTMI", ViewState("EditBooking"), ds_Log.Rows(0).Item("MAgent_no") & "-" & ds_Log.Rows(0).Item("MAgent_name"), ds_Log.Rows(0).Item("Vehicle_no") & "-" & ds_Log.Rows(0).Item("Vehicle_Text"), ds_Log.Rows(0).Item("Date_From") & "-" & ds_Log.Rows(0).Item("Date_To"))
                        ElseIf (Session("Role") & "" = "00005") Then
                            Action = "MRI"
                            If (Status = "MO") Then
                                str = GenBody("รายการจองได้รับการอนุมัติ จากฝ่าย PTMP,PTMI และได้รับการยืนยันค่าประมาณการแล้ว กรุณาทำการตรวจสอบข้อมูลก่อนนำเรือเข้าสู่ท่าเรือ", ViewState("EditBooking"), ds_Log.Rows(0).Item("MAgent_no") & "-" & ds_Log.Rows(0).Item("MAgent_name"), ds_Log.Rows(0).Item("Vehicle_no") & "-" & ds_Log.Rows(0).Item("Vehicle_Text"), ds_Log.Rows(0).Item("Date_From") & "-" & ds_Log.Rows(0).Item("Date_To"))
                            Else
                                str = GenBody("รายการจองได้รับการอนุมัติจากฝ่าย PTMP และ PTMI แล้ว รอการยืนยันค่าประมาณการจากระบบ iPORT", ViewState("EditBooking"), ds_Log.Rows(0).Item("MAgent_no") & "-" & ds_Log.Rows(0).Item("MAgent_name"), ds_Log.Rows(0).Item("Vehicle_no") & "-" & ds_Log.Rows(0).Item("Vehicle_Text"), ds_Log.Rows(0).Item("Date_From") & "-" & ds_Log.Rows(0).Item("Date_To"))
                            End If
                        End If
                        ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('บันทึกข้อมูลสำเร็จ');", True)
                    End If
                    SendMail(ViewState("EditBooking"), Action, str, Status)
                    ViewState("EditBooking") = ""
                    Session("SumTotal") = Nothing
                    Session("CodeMATFree_SAP") = Nothing
                    Session("dsMat_SAP") = Nothing
                    Session("Customer_SAP") = Nothing
                Else
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ไม่สามารถเชื่อมต่อฐานข้อมูลได้ กรุณาทำการ Confirm อีกครั้ง');", True)
                End If
            Else
                clsDB.RollBackTran(tran)
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการบันทึก');", True)
            End If
        Catch ex As Exception
            clsDB.RollBackTran(tran)
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการบันทึก');", True)
        End Try
        Application.UnLock()
        conn.Dispose()
    End Sub
    Private Sub UpdateStatus(ByVal Status As String, ByVal Booking_no As String)
        Dim conn As New System.Data.SqlClient.SqlConnection(connString)
        Dim clsDB As New ClassDatabase
        Dim condition As Boolean = True
        Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
        Dim ds_Log As DataTable = clsGet.Get_Booking_LOG(Booking_no)
        Dim dsBooking As DataTable = clsGet.Get_BookingOneRecord(Booking_no).Tables(0)
        Dim Vps As String = CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("User_name") & " " & DateTime.Now.ToString("yyyyMMdd:HHmmss")
        Dim OldStatus As String = ds_Log.Rows(0).Item("Status") & ""
        Dim ChkOwner As Boolean = False
        Try
            If (ViewState("Owner") <> dsBooking.Rows(0).Item("MAgent_No")) Then
                If (clsGet.Get_Bill_TO_Bulk(Booking_no & "", ViewState("Owner") & "") <> "0") Then
                    ChkOwner = True
                End If
            End If
        Catch ex As Exception

        End Try
        Dim Shifting As String = ""

        Application.Lock()
        conn.Open()

        Dim Booking_Log As String = Date.Now.ToString("yyyyMMddHHmmss")
        tran = clsDB.BeginTran(conn)
        Try
            If (Session("Role") & "" = "00004") Then 'VPS
                If (clsFc.UpdateVPSBooking(Booking_no, txtRemark.Text, Vps, Status, "", "", ds_Log.Rows(0).Item("Marketing_approve") & "", "", ds_Log.Rows(0).Item("Bill_To_no"), ds_Log.Rows(0).Item("Bill_To_name"), Shifting, conn, tran) > 0) Then
                    If (clsFc.InsertBooking_Log(Booking_Log, Booking_no, ds_Log.Rows(0).Item("Booking_Code"), ds_Log.Rows(0).Item("Booking_name"), ds_Log.Rows(0).Item("Vehicle_no"), ds_Log.Rows(0).Item("Vehicle_Text"), ds_Log.Rows(0).Item("Vehicle_LOA"), ds_Log.Rows(0).Item("Vehicle_DWT"), ds_Log.Rows(0).Item("Vehicle_Draft"), ds_Log.Rows(0).Item("Vehicle_GRT"), ds_Log.Rows(0).Item("Date_From"), ds_Log.Rows(0).Item("Date_To"), ds_Log.Rows(0).Item("PORT"), ds_Log.Rows(0).Item("Vehicle_destination"), ds_Log.Rows(0).Item("Vehicle_TypeBuy"), ds_Log.Rows(0).Item("Remark"), Status, txtRemark.Text, Vps, ds_Log.Rows(0).Item("Remark_MRI") & "", ds_Log.Rows(0).Item("MRI_approve") & "", ds_Log.Rows(0).Item("Marketing_approve") & "", ds_Log.Rows(0).Item("Product_name"), ds_Log.Rows(0).Item("Product_Amount"), ds_Log.Rows(0).Item("MAgent_no"), ds_Log.Rows(0).Item("MAgent_name"), ds_Log.Rows(0).Item("SAgent_no"), ds_Log.Rows(0).Item("SAgent_name"), ds_Log.Rows(0).Item("Booking_Date"), ds_Log.Rows(0).Item("Booking_Time"), ds_Log.Rows(0).Item("Buyer"), ds_Log.Rows(0).Item("Seller"), ds_Log.Rows(0).Item("Product_Unit"), ds_Log.Rows(0).Item("File_Upload"), ds_Log.Rows(0).Item("Vehicle_CNTRY"), ds_Log.Rows(0).Item("Lay_Time"), ds_Log.Rows(0).Item("MKT_Product"), ds_Log.Rows(0).Item("MKT_Custom"), ds_Log.Rows(0).Item("MKT_Finance"), ds_Log.Rows(0).Item("BunkerFO_chk"), ds_Log.Rows(0).Item("BunkerDO_chk"), ds_Log.Rows(0).Item("BunkerFO_Point"), ds_Log.Rows(0).Item("BunkerDO_Point"), ds_Log.Rows(0).Item("BunkerDetail"), ds_Log.Rows(0).Item("Water_Point"), ds_Log.Rows(0).Item("MKT_Approve"), ds_Log.Rows(0).Item("Cancel_By"), ds_Log.Rows(0).Item("Cancel_Description"), ds_Log.Rows(0).Item("Vps_Acknowledge"), ds_Log.Rows(0).Item("MKT_Acknowledge"), ds_Log.Rows(0).Item("Payin"), ds_Log.Rows(0).Item("Bill_To_no"), ds_Log.Rows(0).Item("Bill_To_name"), ds_Log.Rows(0).Item("StandardTime"), ds_Log.Rows(0).Item("Credit_Limit"), ds_Log.Rows(0).Item("Status_Pay"), ds_Log.Rows(0).Item("Demurrage"), ds_Log.Rows(0).Item("Demurrage_Money"), ds_Log.Rows(0).Item("Electricity") & "", Shifting, conn, tran) < 1) Then
                        condition = False
                    End If
                Else
                    condition = False
                End If
            ElseIf (Session("Role") & "" = "00005") Then 'MRI
                If (clsFc.UpdateVPSBooking(Booking_no, ds_Log.Rows(0).Item("Remark_VPS"), ds_Log.Rows(0).Item("VPS_approve"), Status, txtRemark.Text, Vps, ds_Log.Rows(0).Item("Marketing_approve") & "", "", ds_Log.Rows(0).Item("Bill_To_no"), ds_Log.Rows(0).Item("Bill_To_name"), Shifting, conn, tran) > 0) Then
                    If (clsFc.InsertBooking_Log(Booking_Log, Booking_no, ds_Log.Rows(0).Item("Booking_Code"), ds_Log.Rows(0).Item("Booking_name"), ds_Log.Rows(0).Item("Vehicle_no"), ds_Log.Rows(0).Item("Vehicle_Text"), ds_Log.Rows(0).Item("Vehicle_LOA"), ds_Log.Rows(0).Item("Vehicle_DWT"), ds_Log.Rows(0).Item("Vehicle_Draft"), ds_Log.Rows(0).Item("Vehicle_GRT"), ds_Log.Rows(0).Item("Date_From"), ds_Log.Rows(0).Item("Date_To"), ds_Log.Rows(0).Item("PORT"), ds_Log.Rows(0).Item("Vehicle_destination"), ds_Log.Rows(0).Item("Vehicle_TypeBuy"), ds_Log.Rows(0).Item("Remark"), Status, ds_Log.Rows(0).Item("Remark_VPS"), ds_Log.Rows(0).Item("VPS_approve"), txtRemark.Text, Vps, ds_Log.Rows(0).Item("Marketing_approve") & "", ds_Log.Rows(0).Item("Product_name"), ds_Log.Rows(0).Item("Product_Amount"), ds_Log.Rows(0).Item("MAgent_no"), ds_Log.Rows(0).Item("MAgent_name"), ds_Log.Rows(0).Item("SAgent_no"), ds_Log.Rows(0).Item("SAgent_name"), ds_Log.Rows(0).Item("Booking_Date"), ds_Log.Rows(0).Item("Booking_Time"), ds_Log.Rows(0).Item("Buyer"), ds_Log.Rows(0).Item("Seller"), ds_Log.Rows(0).Item("Product_Unit"), ds_Log.Rows(0).Item("File_Upload"), ds_Log.Rows(0).Item("Vehicle_CNTRY"), ds_Log.Rows(0).Item("Lay_Time"), ds_Log.Rows(0).Item("MKT_Product"), ds_Log.Rows(0).Item("MKT_Custom"), ds_Log.Rows(0).Item("MKT_Finance"), ds_Log.Rows(0).Item("BunkerFO_chk"), ds_Log.Rows(0).Item("BunkerDO_chk"), ds_Log.Rows(0).Item("BunkerFO_Point"), ds_Log.Rows(0).Item("BunkerDO_Point"), ds_Log.Rows(0).Item("BunkerDetail"), ds_Log.Rows(0).Item("Water_Point"), ds_Log.Rows(0).Item("MKT_Approve"), ds_Log.Rows(0).Item("Cancel_By"), ds_Log.Rows(0).Item("Cancel_Description"), ds_Log.Rows(0).Item("Vps_Acknowledge"), ds_Log.Rows(0).Item("MKT_Acknowledge"), ds_Log.Rows(0).Item("Payin"), ds_Log.Rows(0).Item("Bill_To_no"), ds_Log.Rows(0).Item("Bill_To_name"), ds_Log.Rows(0).Item("StandardTime"), ds_Log.Rows(0).Item("Credit_Limit"), ds_Log.Rows(0).Item("Status_Pay"), ds_Log.Rows(0).Item("Demurrage"), ds_Log.Rows(0).Item("Demurrage_Money"), ds_Log.Rows(0).Item("Electricity") & "", Shifting, conn, tran) < 1) Then
                        condition = False
                    End If
                Else
                    condition = False
                End If
            End If
            If (condition) Then
                If clsDB.CommitTran(tran) Then
                    LoadBOoking()
                    Dim str As String = ""
                    Dim Action As String = ""
                    If (Session("Role") & "" = "00003") Then
                        Action = "MARKETING"
                        If (Status = "MO") Then
                            str = GenBody("รายการจองได้รับการอนุมัติ จากฝ่าย PTMP,PTMI และได้รับการยืนยันค่าประมาณการแล้ว กรุณาทำการตรวจสอบข้อมูลก่อนนำเรือเข้าสู่ท่าเรือ", Booking_no, ds_Log.Rows(0).Item("MAgent_no") & "-" & ds_Log.Rows(0).Item("MAgent_name"), ds_Log.Rows(0).Item("Vehicle_no") & "-" & ds_Log.Rows(0).Item("Vehicle_Text"), ds_Log.Rows(0).Item("Date_From") & "-" & ds_Log.Rows(0).Item("Date_To"))
                        Else
                            str = GenBody("รายการจองได้ถูกทำการ Confirm ค่าประการแล้วสามารถทำการตรวจสอบได้ผ่านระบบ iPORT", Booking_no, ds_Log.Rows(0).Item("MAgent_no") & "-" & ds_Log.Rows(0).Item("MAgent_name"), ds_Log.Rows(0).Item("Vehicle_no") & "-" & ds_Log.Rows(0).Item("Vehicle_Text"), ds_Log.Rows(0).Item("Date_From") & "-" & ds_Log.Rows(0).Item("Date_To"))
                        End If

                        If (radioPayin.SelectedValue = "1") Then
                            If (OldStatus <> "MO") Then
                                'Dim chkedit As Boolean = Create_Credit_Sale(ViewState("EditBooking"), Vps, Status, ViewState("bill_to").ToString().Split("$")(0), ViewState("bill_to").ToString().Split("$")(1), condition)
                                If (condition) Then
                                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ทำการ Confirm ค่าประมาณการเรียบร้อย !! ');", True)
                                    'If (chkedit) Then
                                    '    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ทำการสร้าง  Sale Order เรียบร้อย ');", True)
                                    'Else
                                    '    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('Document cannot be billed due to credit limit check ');", True)
                                    'End If
                                Else
                                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการบันทึกลง SAP');", True)
                                End If
                            Else
                                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('บันทึกข้อมูลสำเร็จ');", True)
                            End If

                        Else
                            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('บันทึกข้อมูลสำเร็จ');", True)
                        End If
                    Else
                        If (Session("Role") & "" = "00004") Then
                            Action = "VPS"
                            str = GenBody("รายการจองได้รับการอนุมัติจากฝ่าย PTMP รอการอนุมัติจากฝ่าย PTMI", Booking_no, ds_Log.Rows(0).Item("MAgent_no") & "-" & ds_Log.Rows(0).Item("MAgent_name"), ds_Log.Rows(0).Item("Vehicle_no") & "-" & ds_Log.Rows(0).Item("Vehicle_Text"), ds_Log.Rows(0).Item("Date_From") & "-" & ds_Log.Rows(0).Item("Date_To"))
                        ElseIf (Session("Role") & "" = "00005") Then
                            Action = "MRI"
                            If (Status = "MO") Then
                                str = GenBody("รายการจองได้รับการอนุมัติ จากฝ่าย PTMP,PTMI และได้รับการยืนยันค่าประมาณการแล้ว กรุณาทำการตรวจสอบข้อมูลก่อนนำเรือเข้าสู่ท่าเรือ", Booking_no, ds_Log.Rows(0).Item("MAgent_no") & "-" & ds_Log.Rows(0).Item("MAgent_name"), ds_Log.Rows(0).Item("Vehicle_no") & "-" & ds_Log.Rows(0).Item("Vehicle_Text"), ds_Log.Rows(0).Item("Date_From") & "-" & ds_Log.Rows(0).Item("Date_To"))
                            Else
                                str = GenBody("รายการจองได้รับการอนุมัติจากฝ่าย PTMP และ PTMI แล้ว รอการยืนยันค่าประมาณการจากระบบ iPORT", Booking_no, ds_Log.Rows(0).Item("MAgent_no") & "-" & ds_Log.Rows(0).Item("MAgent_name"), ds_Log.Rows(0).Item("Vehicle_no") & "-" & ds_Log.Rows(0).Item("Vehicle_Text"), ds_Log.Rows(0).Item("Date_From") & "-" & ds_Log.Rows(0).Item("Date_To"))
                            End If
                        End If
                        ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('บันทึกข้อมูลสำเร็จ');", True)
                    End If
                    ' SendMail(Booking_no, Action, str, Status)
                    ViewState("EditBooking") = ""
                    Session("SumTotal") = Nothing
                    Session("CodeMATFree_SAP") = Nothing
                    Session("dsMat_SAP") = Nothing
                    Session("Customer_SAP") = Nothing
                Else
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ไม่สามารถเชื่อมต่อฐานข้อมูลได้ กรุณาทำการ Confirm อีกครั้ง');", True)
                End If
            Else
                clsDB.RollBackTran(tran)
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการบันทึก1');", True)
            End If
        Catch ex As Exception
            clsDB.RollBackTran(tran)
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการบันทึก2');", True)
        End Try
        Application.UnLock()
        conn.Dispose()
    End Sub

    Private Sub gridTariff_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gridTariff.RowCommand
        Dim Index As Integer = Convert.ToInt32(e.CommandArgument)
        'If (gridItem.PageIndex <> 0) Then
        '    Index = Index Mod (gridItem.PageIndex * 10)
        'End If
        If e.CommandName = "cmdedit" Then
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " document.getElementById('ctl00_contentplaceholder1_EditPopup').src = '../FormPopup/EditMaterialEstimate.aspx';", True)
            Session("indexPopupTariff") = Index
            ModalPopupExtender4.Show()
        ElseIf e.CommandName = "cmddelete" Then
            Dim ds As DataSet = Session("MAT_USE")
            ds.Tables(0).Rows(Index).Delete()
            ds.Tables(0).AcceptChanges()
            Session("MAT_USE") = ds
            gridTariff.PageIndex = 0
            gridTariff.DataSource = Session("MAT_USE")
            gridTariff.DataBind()
        End If
    End Sub

    Private Sub LoadDataCountMAtUSe()
        Dim ds As DataSet = Session("MAT_USE")
        For i = 0 To gridTariff.Rows.Count - 1
            Dim txt As TextBox = CType(gridTariff.Rows(i).FindControl("txtCount"), TextBox)
            Dim chk As CheckBox = CType(gridTariff.Rows(i).FindControl("chk"), CheckBox)
            If (chk.Checked) Then
                ds.Tables(0).Rows(i).Item("MAT_ComputeM") = "Y"
            Else
                ds.Tables(0).Rows(i).Item("MAT_ComputeM") = "N"
            End If
            ' ds.Tables(0).Rows(i).Item("Count") = txt.Text
            ds.AcceptChanges()
        Next
        Session("MAT_USE") = ds
    End Sub

    Private Sub btnCompute_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCompute.Click
        If (checkBeforeCompute()) Then
            LoadDataCountMAtUSe()
            Session("Status_Pay") = ViewState("Status_Pay")
            'If (ViewState("PORT") = "B") Then
            '    If Not (ViewState("OwnerColumn") & "" = "") Then
            '        Dim dsBulk As DataSet = Session("MAT_USE")
            '        Dim dsNewBulk As New DataSet
            '        Dim Owner() As String = ViewState("OwnerColumn").ToString.Split("$")
            '        Dim Count As Integer = 0
            '        For i As Integer = 0 To Owner.Length - 1
            '            Dim _Owner As String = Owner(i).Split("฿")(0)
            '            If (Owner(i).Split("฿")(1) <> "") Then
            '                'ทำการแยก DataTable ของลูกค้าแต่ละคนออกจากกันเลย
            '                Dim dtN As DataTable = dsBulk.Tables(0).Clone
            '                If (dtN.Columns.Count < 13) Then
            '                    dtN.Columns.Add("Owner", GetType(String))
            '                    dtN.AcceptChanges()
            '                End If
            '                For j As Integer = 0 To gridTariff.Rows.Count - 1
            '                    Dim chk As CheckBox = CType(gridTariff.Rows(j).FindControl("chkOwner" & Count + 1), CheckBox)
            '                    If (chk.Checked) Then
            '                        Dim dr As DataRow = dtN.NewRow
            '                        dr.Item("MATERIAL") = gridTariff.DataKeys(j).Values("MATERIAL") & ""
            '                        dr.Item("Text_line") = gridTariff.DataKeys(j).Values("Text_line") & ""
            '                        dr.Item("Unit") = gridTariff.DataKeys(j).Values("Unit") & ""
            '                        dr.Item("Count") = gridTariff.DataKeys(j).Values("Count") & ""
            '                        dr.Item("MAT_Default") = gridTariff.DataKeys(j).Values("MAT_Default") & ""
            '                        dr.Item("KBETR") = gridTariff.DataKeys(j).Values("KBETR") & ""
            '                        dr.Item("KONWA") = gridTariff.DataKeys(j).Values("KONWA") & ""
            '                        dr.Item("MAT_Relation") = gridTariff.DataKeys(j).Values("Mat_Relation") & ""
            '                        dr.Item("MAT_ComputeM") = gridTariff.DataKeys(j).Values("MAT_ComputeM") & ""
            '                        dr.Item("Owner") = _Owner
            '                        dtN.Rows.Add(dr)
            '                        dtN.AcceptChanges()
            '                    End If
            '                Next
            '                Count += 1
            '                dtN.TableName = "Bulk" & Count
            '                dsNewBulk.Tables.Add(dtN.Copy)
            '            End If
            '        Next
            '        Session("MAT_USE") = dsNewBulk
            '    End If
            '
            '     End If
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " document.getElementById('ctl00_contentplaceholder1_framePopup2').src = '../FormPopup/estimate.aspx';", True)
            Session("Booking_no_ESTIMATE") = ViewState("EditBooking")
            ModalPopupExtender2.Show()
        End If

    End Sub

    Private Function checkBeforeCompute() As Boolean
        If Not (ViewState("FREE")) Then
            If (txtid.Text.Trim = "") Then
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการระบุ Main Agent ก่อนทำการคำนวณค่าประมาณการ !!');", True)
                Return False
            End If
        End If

        'If (txtBillTo.Text.Trim() = "") Then
        '    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการระบุ Bill To ก่อนทำการคำนวณค่าประมาณการ !!');", True)
        '    Return False
        'End If
        'If (txtBillTo.Text.Trim <> "") Then
        '    If ((clsGet.Get_BillTo(txtBillTo.Text.Trim().Split("-")(0), AutoCompleteExtender3.ContextKey)).Rows.Count < 1) Then
        '        ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ไม่พบข้อมูล Bill To !!');", True)
        '        Return False
        '    End If
        'End If
        If (radioPayin.SelectedValue = "") Then
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการระบุวิธีการชำระเงินก่อนทำการคำนวณค่าประมาณการ !!');", True)
            Return False
        End If
        If (ViewState("PORT") & "" = "B") Then
            For i As Integer = 0 To gridProduct.Rows.Count - 1
                If (gridProduct.DataKeys(i).Values("Product_no") & "" <> "") Then
                    Dim lbOwnergrid As Label = CType(gridProduct.Rows(i).FindControl("lbOwner"), Label)
                    If (lbOwnergrid.Text = "") Or (lbOwnergrid.Text = "&nbsp;") Then
                        ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการระบุเจ้าของสินค้าก่อนทำการคำนวณค่าประมาณการ !!');", True)
                        Return False
                    End If
                End If

            Next
        End If
        Return True
    End Function

    Private Sub btnLoad_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnLoad.Click
        Dim ds As DataSet = Session("MAT_USE")
        For i As Integer = 0 To ds.Tables(0).Rows.Count - 1
            If (ds.Tables(0).Rows(i).Item("Mat_Compute") & "" = "") Then
                ds.Tables(0).Rows(i).Item("Mat_Compute") = "Y"
            End If
            If (ds.Tables(0).Rows(i).Item("Mat_Free") & "" = "") Then
                ds.Tables(0).Rows(i).Item("Mat_Free") = "N"
            End If
            ds.Tables(0).AcceptChanges()
        Next
        Session("MAT_USE") = ds
        gridTariff.PageIndex = 0
        gridTariff.DataSource = Session("MAT_USE")
        gridTariff.DataBind()
    End Sub

    Private Sub btnSaveBooking_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSaveBooking.Click
        Dim dsMat_SAP As DataSet = Session("dsMat_SAP")
        Dim chkMat As Boolean = False
        For Each dt As DataTable In dsMat_SAP.Tables
            If (dt.Rows.Count > 0) Then
                chkMat = True
            End If
        Next

        If (chkMat) Then
            Dim dt As DataSet = clsGet.Get_BookingOneRecord(ViewState("EditBooking") & "")
            If (dt.Tables(0).Rows(0).Item("MAgent_no") & "" <> "") Then
                Dim dtBooking As DataTable = clsGet.Get_BookingOneRecord(ViewState("EditBooking")).Tables(0)
                If (dtBooking.Rows(0).Item("Status") & "" = "MA") Then
                    UpdateStatus("MO") 'Marketing OK
                Else
                    UpdateStatus(dtBooking.Rows(0).Item("Status") & "")
                End If
            Else
                If (Label23.Text <> "เจ้าของสินค้า") Then
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการระบุ Main Agent ก่อนทำการยืนยันค่าประมาณการ !!');", True)
                End If
            End If
        Else
            Dim dtBooking As DataTable = clsGet.Get_BookingOneRecord(ViewState("EditBooking")).Tables(0)
            If (dtBooking.Rows(0).Item("Status") & "" = "MA") Then
                UpdateStatus("MO") 'Marketing OK
            Else
                UpdateStatus(dtBooking.Rows(0).Item("Status") & "")
            End If
        End If

    End Sub

    Private Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearch.Click
        'ทำการค้นหาข้อมูลเรือและทำการอัพเดตเรือแทข้อมูลที่ Dummy ไว้
        Dim ds As DataTable = clsGet.Get_VEHICLE_DETAIL(txtVessel.Text.Split("-")(0))
        If (ds.Rows.Count = 1) Then
            'พบข้อมูลเรือ
            Dim conn As New System.Data.SqlClient.SqlConnection(connString)
            Dim clsDB As New ClassDatabase
            Dim clsFc As New ClassFunction
            Dim condition As Boolean = True
            Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
            Dim ds_Log As DataTable = clsGet.Get_Booking_LOG(ViewState("EditBooking"))
            Dim Vps As String = CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("User_name") & " " & DateTime.Now.ToString("yyyyMMdd:HHmmss")
            Application.Lock()
            conn.Open()

            Dim Booking_Log As String = Date.Now.ToString("yyyyMMddHHmmss")
            tran = clsDB.BeginTran(conn)
            Try
                If (clsFc.UpdateBookingVehicle(ViewState("EditBooking"), ds.Rows(0).Item("VEHICLE"), ds.Rows(0).Item("VEH_TEXT"), (CDbl(ds.Rows(0).Item("VEH_LENGTH").ToString().Trim()) * 3.281).ToString("##########0.00"), ds.Rows(0).Item("VEH_MAXWGT_C").ToString().Trim(), (CDbl(ds.Rows(0).Item("DRAFT").ToString().Trim()) * 3.281).ToString("##########0.00"), ds.Rows(0).Item("STCMNR").ToString().Trim().Replace("GRT", "").Replace("=", "").Replace("MT", ""), ds.Rows(0).Item("REG_CNTRY") & "", conn, tran) > 0) Then
                    If (clsFc.InsertBooking_Log(Booking_Log, ViewState("EditBooking"), ds_Log.Rows(0).Item("Booking_Code"), ds_Log.Rows(0).Item("Booking_name"), ds.Rows(0).Item("VEHICLE"), ds.Rows(0).Item("VEH_TEXT"), (CDbl(ds.Rows(0).Item("VEH_LENGTH").ToString().Trim()) * 3.281).ToString("##########0.00"), ds.Rows(0).Item("VEH_MAXWGT_C").ToString().Trim(), (CDbl(ds.Rows(0).Item("DRAFT").ToString().Trim()) * 3.281).ToString("##########0.00"), ds.Rows(0).Item("STCMNR").ToString().Trim().Replace("GRT", "").Replace("=", "").Replace("MT", ""), ds_Log.Rows(0).Item("Date_From"), ds_Log.Rows(0).Item("Date_To"), ds_Log.Rows(0).Item("PORT"), ds_Log.Rows(0).Item("Vehicle_destination"), ds_Log.Rows(0).Item("Vehicle_TypeBuy"), ds_Log.Rows(0).Item("Remark"), ds_Log.Rows(0).Item("Status"), ds_Log.Rows(0).Item("Remark_VPS"), ds_Log.Rows(0).Item("VPS_approve"), ds_Log.Rows(0).Item("Remark_MRI"), ds_Log.Rows(0).Item("MRI_approve"), ds_Log.Rows(0).Item("Marketing_approve"), ds_Log.Rows(0).Item("Product_name"), ds_Log.Rows(0).Item("Product_Amount"), ds_Log.Rows(0).Item("MAgent_no"), ds_Log.Rows(0).Item("MAgent_name"), ds_Log.Rows(0).Item("SAgent_no"), ds_Log.Rows(0).Item("SAgent_name"), ds_Log.Rows(0).Item("Booking_Date"), ds_Log.Rows(0).Item("Booking_Time"), ds_Log.Rows(0).Item("Buyer"), ds_Log.Rows(0).Item("Seller"), ds_Log.Rows(0).Item("Product_Unit"), ds_Log.Rows(0).Item("File_Upload"), ds.Rows(0).Item("REG_CNTRY") & "", ds_Log.Rows(0).Item("Lay_Time"), ds_Log.Rows(0).Item("MKT_Product"), ds_Log.Rows(0).Item("MKT_Custom"), ds_Log.Rows(0).Item("MKT_Finance"), ds_Log.Rows(0).Item("BunkerFO_chk"), ds_Log.Rows(0).Item("BunkerDO_chk"), ds_Log.Rows(0).Item("BunkerFO_Point"), ds_Log.Rows(0).Item("BunkerDO_Point"), ds_Log.Rows(0).Item("BunkerDetail"), ds_Log.Rows(0).Item("Water_Point"), ds_Log.Rows(0).Item("MKT_Approve"), ds_Log.Rows(0).Item("Cancel_By"), ds_Log.Rows(0).Item("Cancel_Description"), ds_Log.Rows(0).Item("Vps_Acknowledge"), ds_Log.Rows(0).Item("MKT_Acknowledge"), ds_Log.Rows(0).Item("Payin"), ds_Log.Rows(0).Item("Bill_To_no"), ds_Log.Rows(0).Item("Bill_To_name"), ds_Log.Rows(0).Item("StandardTime"), ds_Log.Rows(0).Item("Credit_Limit"), ds_Log.Rows(0).Item("Status_Pay"), ds_Log.Rows(0).Item("Demurrage"), ds_Log.Rows(0).Item("Demurrage_Money"), ds_Log.Rows(0).Item("Electricity") & "", ds_Log.Rows(0).Item("Shifting") & "", conn, tran) < 1) Then
                        condition = False
                    End If
                End If
                If (condition) Then
                    clsDB.CommitTran(tran)

                    lbVehicle.Text = ds.Rows(0).Item("VEHICLE") & "-" & ds.Rows(0).Item("VEH_TEXT")
                    lbLOA.Text = (CDbl(ds.Rows(0).Item("VEH_LENGTH").ToString().Trim()) * 3.281).ToString("##########0.00")
                    lbDWT.Text = ds.Rows(0).Item("VEH_MAXWGT_C").ToString().Trim()
                    lbDraft.Text = (CDbl(ds.Rows(0).Item("DRAFT").ToString().Trim()) * 3.281).ToString("##########0.00")
                    lbGRT.Text = ds.Rows(0).Item("STCMNR").ToString().Trim().Replace("GRT", "").Replace("=", "").Replace("MT", "")
                    lbNation.Text = ds.Rows(0).Item("REG_CNTRY") & ""
                    rowVehicle.Visible = False
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('บันทึกข้อมูลเรือสำเร็จ');", True)
                Else
                    clsDB.RollBackTran(tran)
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการบันทึก');", True)
                End If
            Catch ex As Exception
                clsDB.RollBackTran(tran)
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการบันทึก');", True)
            End Try
            Application.UnLock()
            conn.Dispose()
        Else
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ไม่พบข้อมูลเรือ!!');", True)
        End If
    End Sub

    Private Sub btnBack_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnBack.Click
        LoadBOoking()
        Timer1_Tick(sender, e)
    End Sub

    Private Sub btnBack2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnBack2.Click
        LoadBOoking()
        Timer1_Tick(sender, e)
    End Sub

    Private Sub ShowRemark(ByVal Booking As String, ByVal ShowMRI As Boolean)
        Dim RemarkVPS As String = ""
        Dim FirstRemarkVPS As Boolean = True
        Dim TimeCreateRemark As String = ""
        Dim dsRemark As DataTable = clsGet.Get_Booking_LogRemarkVPS(Booking, "VPS")
        If (dsRemark.Rows.Count > 0) Then
            rowRemarkVPS.Visible = True
            Dim old As String = ""
            For Each drVPS As DataRow In dsRemark.Rows
                If (drVPS.Item("Remark_VPS") & "" <> "") Then
                    If (old <> drVPS.Item("Remark_VPS") & "") Then
                        old = drVPS.Item("Remark_VPS") & ""
                        TimeCreateRemark = drVPS.Item("Booking_log")
                        If (FirstRemarkVPS) Then
                            RemarkVPS = TimeCreateRemark.Substring(6, 2) & "/" & TimeCreateRemark.Substring(4, 2) & "/" & TimeCreateRemark.Substring(0, 4) & " " & TimeCreateRemark.Substring(8, 2) & ":" & TimeCreateRemark.Substring(10, 2) & " - " & drVPS.Item("Remark_VPS")
                            FirstRemarkVPS = False
                        Else
                            RemarkVPS &= "<BR />" & TimeCreateRemark.Substring(6, 2) & "/" & TimeCreateRemark.Substring(4, 2) & "/" & TimeCreateRemark.Substring(0, 4) & " " & TimeCreateRemark.Substring(8, 2) & ":" & TimeCreateRemark.Substring(10, 2) & " - " & drVPS.Item("Remark_VPS")
                        End If
                    End If

                End If
            Next
            If (RemarkVPS.Trim() = "") Then
                lbRemark_VPS.Text = String.Empty
                rowRemarkVPS.Visible = False
            Else
                lbRemark_VPS.Text = RemarkVPS
            End If

        Else
            lbRemark_VPS.Text = String.Empty
            rowRemarkVPS.Visible = False
        End If

        If (ShowMRI) Then
            Dim RemarkMRI As String = ""
            Dim FirstRemarkMRI As Boolean = True
            TimeCreateRemark = ""
            dsRemark = clsGet.Get_Booking_LogRemarkVPS(Booking, "MRI")
            If (dsRemark.Rows.Count > 0) Then
                rowRemarkMRI.Visible = True
                Dim old As String = ""
                For Each drVPS As DataRow In dsRemark.Rows
                    If (drVPS.Item("Remark_MRI") & "" <> "") Then
                        If (old <> drVPS.Item("Remark_MRI") & "") Then
                            old = drVPS.Item("Remark_MRI") & ""
                            TimeCreateRemark = drVPS.Item("Booking_log")
                            If (FirstRemarkMRI) Then
                                RemarkMRI = TimeCreateRemark.Substring(6, 2) & "/" & TimeCreateRemark.Substring(4, 2) & "/" & TimeCreateRemark.Substring(0, 4) & " " & TimeCreateRemark.Substring(8, 2) & ":" & TimeCreateRemark.Substring(10, 2) & " - " & drVPS.Item("Remark_MRI")
                                FirstRemarkMRI = False
                            Else
                                RemarkMRI &= "<BR />" & TimeCreateRemark.Substring(6, 2) & "/" & TimeCreateRemark.Substring(4, 2) & "/" & TimeCreateRemark.Substring(0, 4) & " " & TimeCreateRemark.Substring(8, 2) & ":" & TimeCreateRemark.Substring(10, 2) & " - " & drVPS.Item("Remark_MRI")
                            End If
                        End If

                    End If
                Next
                If (RemarkMRI.Trim() = "") Then
                    lbRemark_MRI.Text = String.Empty
                    rowRemarkMRI.Visible = False
                Else
                    lbRemark_MRI.Text = RemarkMRI
                End If

            Else
                lbRemark_MRI.Text = String.Empty
                rowRemarkMRI.Visible = False
            End If
        End If

    End Sub

    Private Sub BtnBackView_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnBackView.Click
        If (Session("Ship_View") Is Nothing) Then
            LoadBOoking()
            Timer1_Tick(sender, e)
        Else
            Response.Redirect("../Form/frm_ShipSchedule.aspx?P4=O", True)
        End If

    End Sub

    Private Sub gridProduct_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gridProduct.RowCommand
        Dim Index As Integer = Convert.ToInt32(e.CommandArgument)
        If e.CommandName = "updateOwner" Then
            Dim txtOwner As TextBox = CType(gridProduct.Rows(Index).FindControl("txtOwner"), TextBox)
            If (txtOwner.Text <> "") Then
                If ((clsGet.Get_Customer(txtOwner.Text.Trim().Split("-")(0))).Rows.Count < 1) Then
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ไม่พบข้อมูลเจ้าของสินค้า !!');", True)
                Else
                    'ทำการ Update
                    Dim conn As New System.Data.SqlClient.SqlConnection(connString)
                    Dim clsDB As New ClassDatabase
                    Dim clsFc As New ClassFunction
                    Dim condition As Boolean = True
                    Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
                    Dim NameOwner As String = ""
                    Dim OwnerLoop() As String = txtOwner.Text.Split("-")
                    For i As Integer = 0 To OwnerLoop.Length - 1
                        If (i <> 0) Then
                            NameOwner &= "-" & OwnerLoop(i).ToString()
                        End If
                    Next
                    NameOwner = NameOwner.Substring(1, NameOwner.Length - 1)
                    Application.Lock()
                    conn.Open()
                    tran = clsDB.BeginTran(conn)
                    Try
                        If (clsFc.UpdateProduct_Owner(gridProduct.DataKeys(Index).Values("Booking_no"), gridProduct.DataKeys(Index).Values("Product_no"), txtOwner.Text.Split("-")(0), NameOwner, conn, tran) < 1) Then
                            condition = False
                        End If
                        If (condition) Then
                            clsDB.CommitTran(tran)
                            Session("Product_popup") = clsGet.Get_Booking_Product(ViewState("EditBooking"))
                            gridProduct.PageIndex = 0
                            gridProduct.DataSource = Session("Product_popup")
                            gridProduct.DataBind()
                            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('บันทึกข้อมูล Agent สำเร็จ');", True)
                        Else
                            clsDB.RollBackTran(tran)
                            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการบันทึก');", True)
                        End If
                    Catch ex As Exception
                        ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการบันทึก');", True)
                    End Try

                End If
            Else
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการระบุเจ้าของสินค้าก่อนทำการ Update !!');", True)
            End If
        ElseIf e.CommandName = "updateProduct" Then
            Dim txtProductName As TextBox = CType(gridProduct.Rows(Index).FindControl("txtProductName"), TextBox)
            Dim product As DataTable = clsGet.Get_Product_no(txtProductName.Text)
            If product.Rows.Count <> 1 Then
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", "alert('ไม่พบข้อมูลสินค้า !!');", True)
                Exit Sub
            End If

            'ทำการ Update
            Dim conn As New System.Data.SqlClient.SqlConnection(connString)
            Dim clsDB As New ClassDatabase
            Dim clsFc As New ClassFunction
            Dim condition As Boolean = True
            Dim tran As System.Data.SqlClient.SqlTransaction = Nothing

            Application.Lock()
            conn.Open()
            tran = clsDB.BeginTran(conn)
            Try
                If (clsFc.UpdateBooking_Product(gridProduct.DataKeys(Index).Values("Booking_no"), product.Rows(0).Item("Product_no"), txtProductName.Text, product.Rows(0).Item("Group_no"), product.Rows(0).Item("Group_name"), conn, tran) < 1) Then
                    condition = False
                End If
                If (condition) Then
                    clsDB.CommitTran(tran)
                    Session("Product_popup") = clsGet.Get_Booking_Product(ViewState("EditBooking"))
                    gridProduct.PageIndex = 0
                    gridProduct.DataSource = Session("Product_popup")
                    gridProduct.DataBind()
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('บันทึกข้อมูล Product สำเร็จ');", True)
                Else
                    clsDB.RollBackTran(tran)
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการบันทึก');", True)
                End If
            Catch ex As Exception
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการบันทึก');", True)
            End Try

        End If
    End Sub

    Private Sub gridProduct_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gridProduct.RowDataBound
        If e.Row.RowType = DataControlRowType.DataRow Then
            If (gridProduct.DataKeys(e.Row.RowIndex).Values("Product_Event") & "" = "L") Then
                e.Row.Cells(0).Text = "Load"
            ElseIf (gridProduct.DataKeys(e.Row.RowIndex).Values("Product_Event") & "" = "D") Then
                e.Row.Cells(0).Text = "Disch"
            ElseIf (gridProduct.DataKeys(e.Row.RowIndex).Values("Product_Event") & "" = "R") Then
                e.Row.Cells(0).Text = "Load(IRPC)"
            ElseIf (gridProduct.DataKeys(e.Row.RowIndex).Values("Product_Event") & "" = "I") Then
                e.Row.Cells(0).Text = "Disch(IRPC)"
            End If
            If (ViewState("PORT") & "" = "B") Then
                Dim lbOwner As Label = CType(e.Row.FindControl("lbOwner"), Label)
                Dim txtOwner As TextBox = CType(e.Row.FindControl("txtOwner"), TextBox)
                Dim btnOwner As Button = CType(e.Row.FindControl("btnOwner"), Button)
                If (gridProduct.DataKeys(e.Row.RowIndex).Values("Product_no") & "" <> "") Then
                    If (gridProduct.DataKeys(e.Row.RowIndex).Values("Owner_Product_no") & "" = "") Then
                        txtOwner.Visible = True
                        lbOwner.Visible = False
                        btnOwner.Visible = True
                    Else
                        lbOwner.Visible = True
                        txtOwner.Visible = False
                        btnOwner.Visible = False
                    End If
                End If
            End If
            Dim AutoComplete As AjaxControlToolkit.AutoCompleteExtender = CType(e.Row.FindControl("AutoCompleteExtenproduct"), AjaxControlToolkit.AutoCompleteExtender)
            AutoComplete.ContextKey = ViewState("PORT")
            Dim lbProductName As Label = CType(e.Row.FindControl("lbProductName"), Label)
            Dim txtProductName As TextBox = CType(e.Row.FindControl("txtProductName"), TextBox)
            Dim btnProductName As Button = CType(e.Row.FindControl("btnProductName"), Button)
            If (gridProduct.DataKeys(e.Row.RowIndex).Values("Group_no") & "" = "0000000000") Then
                txtProductName.Visible = True
                lbProductName.Visible = False
                btnProductName.Visible = True
                e.Row.BackColor = Drawing.Color.Red
                Accordion2.SelectedIndex = 0
            Else
                lbProductName.Visible = True
                txtProductName.Visible = False
                btnProductName.Visible = False
            End If
        End If
    End Sub

    Private Sub gridItem_RowCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gridItem.RowCreated
        If e.Row.RowType = DataControlRowType.Header Then
            Dim Grid As GridView = CType(sender, GridView)
            e.Row.Cells.Clear()
            Dim GridRow As GridViewRow = New GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert)
            Dim GridRow1 As GridViewRow = New GridViewRow(1, 0, DataControlRowType.Header, DataControlRowState.Insert)

            Dim table As TableCell = New TableCell()
            Dim checkAll As CheckBox = New CheckBox()
            checkAll.ID = "checkAll"

            table.Controls.Add(checkAll)
            'table.Text = "xxx"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.CssClass = "locked"
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "BOOKING NO."
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.CssClass = "locked"
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "VESSEL NAME"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.CssClass = "locked"
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "STATUS"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "LAY CAN/LAY DAY"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "REQUIRE DATE/TIME"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "LAY TIME"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)


            table = New TableCell()
            table.Text = "ATTACHMENT"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "COMMODITY"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "QUANTITY"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "UNIT"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "BUYER"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)


            table = New TableCell()
            table.Text = "SELLER(12)"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "APPROVE BY MKT"
            table.HorizontalAlign = HorizontalAlign.Center
            table.ColumnSpan = 5
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "APPROVE BY"
            table.HorizontalAlign = HorizontalAlign.Center
            table.ColumnSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "TARIFF"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "AGENT"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "WHARF"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "PLAN BERTH DATE"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "PLAN BERTH TIME"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "PLAN DEPART DATE"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "PLAN DEPART TIME"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "CONFIRM PLAN BERTH"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "REMAIN LAYTIME(ESTIMATE)"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = "REMARK"
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            table = New TableCell()
            table.Text = ""
            table.HorizontalAlign = HorizontalAlign.Center
            table.RowSpan = 2
            table.Wrap = True
            GridRow1.Cells.Add(table)

            Grid.Controls(0).Controls.AddAt(0, GridRow1)

            table = New TableCell()
            table.Text = "PRODUCT"
            table.HorizontalAlign = HorizontalAlign.Center
            table.Wrap = True
            GridRow.Cells.Add(table)

            table = New TableCell()
            table.Text = "CUSTOM"
            table.HorizontalAlign = HorizontalAlign.Center
            table.Wrap = True
            GridRow.Cells.Add(table)

            table = New TableCell()
            table.Text = "FINANCE"
            table.HorizontalAlign = HorizontalAlign.Center
            table.Wrap = True
            GridRow.Cells.Add(table)

            table = New TableCell()
            table.Text = "DEMURRAGE"
            table.HorizontalAlign = HorizontalAlign.Center
            table.Wrap = True
            GridRow.Cells.Add(table)

            table = New TableCell()
            table.Text = "TERM"
            table.HorizontalAlign = HorizontalAlign.Center
            table.Wrap = True
            GridRow.Cells.Add(table)

            table = New TableCell()
            table.Text = "PTMP"
            table.HorizontalAlign = HorizontalAlign.Center
            table.Wrap = True
            GridRow.Cells.Add(table)

            table = New TableCell()
            table.Text = "PTMI"
            table.HorizontalAlign = HorizontalAlign.Center
            table.Wrap = True
            GridRow.Cells.Add(table)

            Grid.Controls(0).Controls.AddAt(1, GridRow)
        End If
    End Sub

    Private Sub gridTariff_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gridTariff.RowDataBound
        If e.Row.RowType = DataControlRowType.DataRow Then
            ' Dim txtCount As TextBox = CType(e.Row.FindControl("txtCount"), TextBox)

            Dim imgedit As ImageButton = CType(e.Row.FindControl("imgedit"), ImageButton)
            If (gridTariff.DataKeys(e.Row.RowIndex).Values("MAT_Relation") & "" = "Y") Then
                'txtCount.Visible = False
                'txtCount.Enabled = False
                e.Row.Cells(3).Text = "-"
                'e.Row.Cells(4).Text = "-"
                imgedit.Visible = False
            End If
            'Dim chk As CheckBox = CType(e.Row.FindControl("chk"), CheckBox)
            'If (gridTariff.DataKeys(e.Row.RowIndex).Values("MAT_ComputeM") & "" = "Y") Then
            '    chk.Checked = True
            'Else
            '    chk.Checked = False
            'End If
        End If
    End Sub

    Private Sub btnSubAgent_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubAgent.Click
        If (txtid.Text.Trim <> "") Then
            If ((clsGet.Get_Customer(txtid.Text.Trim().Split("-")(0))).Rows.Count < 1) Then
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ไม่พบข้อมูล Sub Agent !!');", True)
                Exit Sub
            End If
        End If
        If (txtAgent.Text.Trim <> "") Then
            If ((clsGet.Get_Customer(txtAgent.Text.Trim().Split("-")(0))).Rows.Count < 1) Then
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ไม่พบข้อมูล Main Agent !!');", True)
                Exit Sub
            End If
        End If
        If (txtid.Text.Split("-")(0) = "999999999") Then
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ไม่สามารถให้ IRPC เป็น Main Agent ได้ !!');", True)
            Exit Sub
        End If
        If (txtAgent.Text.Split("-")(0) = "999999999") Then
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ไม่สามารถให้ IRPC เป็น Sub Agent ได้  !!');", True)
            Exit Sub
        End If
        If (txtid.Text.Trim <> "") Or (txtAgent.Text.Trim <> "") Then
            Dim MAgent_no As String = ""
            Dim MAgent_name As String = ""
            Dim SAgent_no As String = ""
            Dim SAgent_name As String = ""
            If (txtid.Text.Trim() <> "") Then
                MAgent_no = txtid.Text.Split("-")(0)
                MAgent_name = txtid.Text.Split("-")(1)
            End If
            If (txtAgent.Text.Trim() <> "") Then
                SAgent_no = txtAgent.Text.Split("-")(0)
                SAgent_name = txtAgent.Text.Split("-")(1)
            End If

            Dim conn As New System.Data.SqlClient.SqlConnection(connString)
            Dim clsDB As New ClassDatabase
            Dim clsFc As New ClassFunction
            Dim condition As Boolean = True
            Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
            Dim ds_Log As DataTable = clsGet.Get_Booking_LOG(ViewState("EditBooking"))
            Dim Vps As String = CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("User_name") & " " & DateTime.Now.ToString("yyyyMMdd:HHmmss")
            Application.Lock()
            conn.Open()

            Dim Booking_Log As String = Date.Now.ToString("yyyyMMddHHmmss")
            tran = clsDB.BeginTran(conn)
            Try

                If (clsFc.UpdateBookingAgent(ViewState("EditBooking"), MAgent_no, MAgent_name, SAgent_no, SAgent_name, conn, tran) > 0) Then
                    If (clsFc.InsertBooking_Log(Booking_Log, ViewState("EditBooking"), ds_Log.Rows(0).Item("Booking_Code"), ds_Log.Rows(0).Item("Booking_name"), ds_Log.Rows(0).Item("Vehicle_no"), ds_Log.Rows(0).Item("Vehicle_Text"), ds_Log.Rows(0).Item("Vehicle_LOA"), ds_Log.Rows(0).Item("Vehicle_DWT"), ds_Log.Rows(0).Item("Vehicle_Draft"), ds_Log.Rows(0).Item("Vehicle_GRT"), ds_Log.Rows(0).Item("Date_From"), ds_Log.Rows(0).Item("Date_To"), ds_Log.Rows(0).Item("PORT"), ds_Log.Rows(0).Item("Vehicle_destination"), ds_Log.Rows(0).Item("Vehicle_TypeBuy"), ds_Log.Rows(0).Item("Remark"), ds_Log.Rows(0).Item("Status"), ds_Log.Rows(0).Item("Remark_VPS"), ds_Log.Rows(0).Item("VPS_approve"), ds_Log.Rows(0).Item("Remark_MRI"), ds_Log.Rows(0).Item("MRI_approve"), ds_Log.Rows(0).Item("Marketing_approve"), ds_Log.Rows(0).Item("Product_name"), ds_Log.Rows(0).Item("Product_Amount"), MAgent_no, MAgent_name, SAgent_no, SAgent_name, ds_Log.Rows(0).Item("Booking_Date"), ds_Log.Rows(0).Item("Booking_Time"), ds_Log.Rows(0).Item("Buyer"), ds_Log.Rows(0).Item("Seller"), ds_Log.Rows(0).Item("Product_Unit"), ds_Log.Rows(0).Item("File_Upload"), ds_Log.Rows(0).Item("Vehicle_CNTRY"), ds_Log.Rows(0).Item("Lay_Time"), ds_Log.Rows(0).Item("MKT_Product"), ds_Log.Rows(0).Item("MKT_Custom"), ds_Log.Rows(0).Item("MKT_Finance"), ds_Log.Rows(0).Item("BunkerFO_chk"), ds_Log.Rows(0).Item("BunkerDO_chk"), ds_Log.Rows(0).Item("BunkerFO_Point"), ds_Log.Rows(0).Item("BunkerDO_Point"), ds_Log.Rows(0).Item("BunkerDetail") & "", ds_Log.Rows(0).Item("Water_Point") & "", ds_Log.Rows(0).Item("MKT_Approve") & "", ds_Log.Rows(0).Item("Cancel_By") & "", ds_Log.Rows(0).Item("Cancel_Description") & "", ds_Log.Rows(0).Item("Vps_Acknowledge") & "", ds_Log.Rows(0).Item("MKT_Acknowledge") & "", ds_Log.Rows(0).Item("Payin"), ds_Log.Rows(0).Item("Bill_To_no"), ds_Log.Rows(0).Item("Bill_To_name"), ds_Log.Rows(0).Item("StandardTime"), ds_Log.Rows(0).Item("Credit_Limit"), ds_Log.Rows(0).Item("Status_Pay"), ds_Log.Rows(0).Item("Demurrage"), ds_Log.Rows(0).Item("Demurrage_Money"), ds_Log.Rows(0).Item("Electricity") & "", ds_Log.Rows(0).Item("Shifting") & "", conn, tran) < 1) Then
                        condition = False
                    End If
                End If
                If (condition) Then
                    clsDB.CommitTran(tran)
                    If (txtid.Text.Trim() <> "") Then
                        AutoCompleteExtender3.ContextKey = MAgent_no
                        Dim Payin As String = clsGet.Get_DefaultPayin(txtid.Text.Split("-")(0))
                        If Not (radioPayin.Items.FindByValue(Payin) Is Nothing) Then
                            radioPayin.SelectedValue = Payin
                        End If
                    End If
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('บันทึกข้อมูล Agent สำเร็จ');", True)
                Else
                    clsDB.RollBackTran(tran)
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการบันทึก');", True)
                End If
            Catch ex As Exception

            End Try

        Else
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการระบุ Main Agent หรือ Sub Agent ก่อนทำการ Update !!');", True)
        End If

    End Sub

    Public Function CreateDatasetProduct() As DataTable
        Dim ds As New DataSet
        Dim dt As New DataTable
        Dim dr As DataRow
        ds.Tables.Add(dt)
        dt.Columns.Add("Product_no", GetType(String))
        dt.Columns.Add("Product_name", GetType(String))
        dt.Columns.Add("Product_Amount", GetType(String))
        dt.Columns.Add("Product_Event", GetType(String))
        dt.Columns.Add("Product_Description", GetType(String))
        dt.Columns.Add("Product_Unit", GetType(String))
        dt.Columns.Add("Group_name", GetType(String))
        dt.Columns.Add("Group_no", GetType(String))
        dt.Columns.Add("Product_BUYER_no", GetType(String))
        dt.Columns.Add("Product_BUYER_name", GetType(String))
        dt.Columns.Add("Product_SELLER_no", GetType(String))
        dt.Columns.Add("Product_SELLER_name", GetType(String))
        dt.Columns.Add("LoadDestination", GetType(String))
        dt.Columns.Add("DischDestination", GetType(String))
        dt.Columns.Add("DestinationShow", GetType(String))
        dt.Columns.Add("Owner_Product_no", GetType(String))
        dt.Columns.Add("Owner_Product_name", GetType(String))
        dr = ds.Tables(0).NewRow
        dr.Item("Product_no") = ""
        dr.Item("Product_name") = ""
        dr.Item("Product_Amount") = ""
        dr.Item("Product_Event") = ""
        dr.Item("Product_Description") = ""
        dr.Item("Product_Unit") = ""
        dr.Item("Group_name") = ""
        dr.Item("Group_no") = ""
        dr.Item("Product_BUYER_no") = ""
        dr.Item("Product_BUYER_name") = ""
        dr.Item("Product_SELLER_no") = ""
        dr.Item("Product_SELLER_name") = ""
        dr.Item("LoadDestination") = ""
        dr.Item("DischDestination") = ""
        dr.Item("DestinationShow") = ""
        dr.Item("Owner_Product_no") = ""
        dr.Item("Owner_Product_name") = ""
        ds.Tables(0).Rows.Add(dr)
        ds.Tables(0).AcceptChanges()
        Return ds.Tables(0)
    End Function

    Private Sub btnBackSaleMKT_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnBackSaleMKT.Click
        LoadBOoking()
        Timer1_Tick(sender, e)
    End Sub

    Private Sub btnSaveApprove_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSaveApprove.Click
        SaveEventProduct_Custom_Finance("Sale")
    End Sub

    Private Sub SaveEventProduct_Custom_Finance(ByVal Type As String)
        Dim conn As New System.Data.SqlClient.SqlConnection(connString)
        Dim clsDB As New ClassDatabase
        Dim clsFc As New ClassFunction
        Dim condition As Boolean = True
        Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
        Dim ds_Log As DataTable = clsGet.Get_Booking_LOG(ViewState("EditBooking"))
        Dim Sale As String = CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("User_name") & " " & DateTime.Now.ToString("yyyyMMdd:HHmmss")
        Dim Product As String = ""
        Dim Custom As String = ""
        Dim Finance As String = ""
        If (Type = "Sale") Then
            For Each li As ListItem In chkApprove.Items
                If (li.Selected) Then
                    Select Case li.Text
                        Case "Product" : Product = "Y"
                        Case "Custom" : Custom = "Y"
                        Case "Finance" : Finance = "Y"
                    End Select
                Else
                    Select Case li.Text
                        Case "Product" : Product = "N"
                        Case "Custom" : Custom = "N"
                        Case "Finance" : Finance = "N"
                    End Select
                End If
            Next
        Else
            For Each li As ListItem In chkApproveForVPS.Items
                If (li.Selected) Then
                    Select Case li.Text
                        Case "Product" : Product = "Y"
                        Case "Custom" : Custom = "Y"
                        Case "Finance" : Finance = "Y"
                    End Select
                Else
                    Select Case li.Text
                        Case "Product" : Product = "N"
                        Case "Custom" : Custom = "N"
                        Case "Finance" : Finance = "N"
                    End Select
                End If
            Next
        End If
        Dim shifting As String = ""

        Application.Lock()
        conn.Open()

        Dim Booking_Log As String = Date.Now.ToString("yyyyMMddHHmmss")
        tran = clsDB.BeginTran(conn)
        Try
            If (Type = "Sale") Then
                If (clsFc.UpdateSaleBooking(ViewState("EditBooking"), Product, Custom, Finance, Sale, txtDate.Text, txtDateTo.Text, shifting, conn, tran) > 0) Then
                    If (clsFc.InsertBooking_Log(Booking_Log, ViewState("EditBooking"), ds_Log.Rows(0).Item("Booking_Code"), ds_Log.Rows(0).Item("Booking_name"), ds_Log.Rows(0).Item("Vehicle_no"), ds_Log.Rows(0).Item("Vehicle_Text"), ds_Log.Rows(0).Item("Vehicle_LOA"), ds_Log.Rows(0).Item("Vehicle_DWT"), ds_Log.Rows(0).Item("Vehicle_Draft"), ds_Log.Rows(0).Item("Vehicle_GRT"), txtDate.Text, txtDateTo.Text, ds_Log.Rows(0).Item("PORT"), ds_Log.Rows(0).Item("Vehicle_destination"), ds_Log.Rows(0).Item("Vehicle_TypeBuy"), ds_Log.Rows(0).Item("Remark"), ds_Log.Rows(0).Item("Status"), ds_Log.Rows(0).Item("Remark_VPS"), ds_Log.Rows(0).Item("VPS_Approve"), ds_Log.Rows(0).Item("Remark_MRI"), ds_Log.Rows(0).Item("MRI_Approve"), ds_Log.Rows(0).Item("Marketing_Approve"), ds_Log.Rows(0).Item("Product_name"), ds_Log.Rows(0).Item("Product_Amount"), ds_Log.Rows(0).Item("MAgent_no"), ds_Log.Rows(0).Item("MAgent_name"), ds_Log.Rows(0).Item("SAgent_no"), ds_Log.Rows(0).Item("SAgent_name"), ds_Log.Rows(0).Item("Booking_Date"), ds_Log.Rows(0).Item("Booking_Time"), ds_Log.Rows(0).Item("Buyer"), ds_Log.Rows(0).Item("Seller"), ds_Log.Rows(0).Item("Product_Unit"), ds_Log.Rows(0).Item("File_Upload"), ds_Log.Rows(0).Item("Vehicle_CNTRY"), ds_Log.Rows(0).Item("Lay_Time"), Product, Custom, Finance, ds_Log.Rows(0).Item("BunkerFO_chk"), ds_Log.Rows(0).Item("BunkerDO_chk"), ds_Log.Rows(0).Item("BunkerFO_Point"), ds_Log.Rows(0).Item("BunkerDO_Point"), ds_Log.Rows(0).Item("BunkerDetail"), ds_Log.Rows(0).Item("Water_Point"), Sale, ds_Log.Rows(0).Item("Cancel_By"), ds_Log.Rows(0).Item("Cancel_Description"), ds_Log.Rows(0).Item("Vps_Acknowledge"), ds_Log.Rows(0).Item("MKT_Acknowledge"), ds_Log.Rows(0).Item("Payin"), ds_Log.Rows(0).Item("Bill_To_no"), ds_Log.Rows(0).Item("Bill_To_name"), ds_Log.Rows(0).Item("StandardTime"), ds_Log.Rows(0).Item("Credit_Limit"), ds_Log.Rows(0).Item("Status_Pay"), ds_Log.Rows(0).Item("Demurrage"), ds_Log.Rows(0).Item("Demurrage_Money"), ds_Log.Rows(0).Item("Electricity") & "", shifting, conn, tran) < 1) Then
                        condition = False
                    End If
                End If
            Else
                If (clsFc.UpdateSaleBooking(ViewState("EditBooking"), Product, Custom, Finance, Sale, ds_Log.Rows(0).Item("Date_From"), ds_Log.Rows(0).Item("Date_To"), shifting, conn, tran) > 0) Then
                    If (clsFc.InsertBooking_Log(Booking_Log, ViewState("EditBooking"), ds_Log.Rows(0).Item("Booking_Code"), ds_Log.Rows(0).Item("Booking_name"), ds_Log.Rows(0).Item("Vehicle_no"), ds_Log.Rows(0).Item("Vehicle_Text"), ds_Log.Rows(0).Item("Vehicle_LOA"), ds_Log.Rows(0).Item("Vehicle_DWT"), ds_Log.Rows(0).Item("Vehicle_Draft"), ds_Log.Rows(0).Item("Vehicle_GRT"), ds_Log.Rows(0).Item("Date_From"), ds_Log.Rows(0).Item("Date_To"), ds_Log.Rows(0).Item("PORT"), ds_Log.Rows(0).Item("Vehicle_destination"), ds_Log.Rows(0).Item("Vehicle_TypeBuy"), ds_Log.Rows(0).Item("Remark"), ds_Log.Rows(0).Item("Status"), ds_Log.Rows(0).Item("Remark_VPS"), ds_Log.Rows(0).Item("VPS_Approve"), ds_Log.Rows(0).Item("Remark_MRI"), ds_Log.Rows(0).Item("MRI_Approve"), ds_Log.Rows(0).Item("Marketing_Approve"), ds_Log.Rows(0).Item("Product_name"), ds_Log.Rows(0).Item("Product_Amount"), ds_Log.Rows(0).Item("MAgent_no"), ds_Log.Rows(0).Item("MAgent_name"), ds_Log.Rows(0).Item("SAgent_no"), ds_Log.Rows(0).Item("SAgent_name"), ds_Log.Rows(0).Item("Booking_Date"), ds_Log.Rows(0).Item("Booking_Time"), ds_Log.Rows(0).Item("Buyer"), ds_Log.Rows(0).Item("Seller"), ds_Log.Rows(0).Item("Product_Unit"), ds_Log.Rows(0).Item("File_Upload"), ds_Log.Rows(0).Item("Vehicle_CNTRY"), ds_Log.Rows(0).Item("Lay_Time"), Product, Custom, Finance, ds_Log.Rows(0).Item("BunkerFO_chk"), ds_Log.Rows(0).Item("BunkerDO_chk"), ds_Log.Rows(0).Item("BunkerFO_Point"), ds_Log.Rows(0).Item("BunkerDO_Point"), ds_Log.Rows(0).Item("BunkerDetail"), ds_Log.Rows(0).Item("Water_Point"), Sale, ds_Log.Rows(0).Item("Cancel_By"), ds_Log.Rows(0).Item("Cancel_Description"), ds_Log.Rows(0).Item("Vps_Acknowledge"), ds_Log.Rows(0).Item("MKT_Acknowledge"), ds_Log.Rows(0).Item("Payin"), ds_Log.Rows(0).Item("Bill_To_no"), ds_Log.Rows(0).Item("Bill_To_name"), ds_Log.Rows(0).Item("StandardTime"), ds_Log.Rows(0).Item("Credit_Limit"), ds_Log.Rows(0).Item("Status_Pay"), ds_Log.Rows(0).Item("Demurrage"), ds_Log.Rows(0).Item("Demurrage_Money"), ds_Log.Rows(0).Item("Electricity") & "", shifting, conn, tran) < 1) Then
                        condition = False
                    End If
                End If
            End If

            If (condition) Then
                clsDB.CommitTran(tran)
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('บันทึกข้อมูลเรียบร้อย');", True)
                If (Session("Ship_View") Is Nothing) Then
                    LoadBOoking()
                Else
                    Response.Redirect("../Form/frm_ShipSchedule.aspx?P4=O", True)
                End If
            Else
                clsDB.RollBackTran(tran)
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการบันทึก');", True)
            End If
        Catch ex As Exception
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการบันทึก !!');", True)
        End Try
    End Sub

    Private Sub btnReject_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnReject.Click
        'Cancel By VPS or MRI 
        Session("StatusCancel") = "VPSMRI"
        ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " document.getElementById('ctl00_contentplaceholder1_CancelPopup').src = '../FormPopup/Cancel_popup.aspx?Type=Manage';", True)
        ModalPopupExtender6.Show()
    End Sub

    Private Sub btnCancle2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancle2.Click
        'Cancel By Marketing 
        Session("StatusCancel") = "MARKETING"
        ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " document.getElementById('ctl00_contentplaceholder1_CancelPopup').src = '../FormPopup/Cancel_popup.aspx?Type=Manage';", True)
        ModalPopupExtender6.Show()
    End Sub
    Private Function CNDN_REQUEST(ByVal IPROT_NUMBER As String, ByVal Biiling As String, ByVal Due_Date As String, ByRef EX_Sale As String, ByVal dt As DataTable, ByRef CNDN_Quatity As SAP_IPORT.ZBAPI_CN_DN_ITEMS, ByRef CNDN_TABLE_Quatity As SAP_IPORT.ZBAPI_CN_DN_ITEMSTable, ByRef ZBABI_RET_Quatity As SAP_IPORT.BAPIRET1Table) As Boolean
        Try
            Dim ClassSAP As New Class_SAP
            Dim SAP_Data As Object = ClassSAP.SAP_OPEN()
            '*****************************
            'ทำการเปลี่ยน Quatity ก่อน
            '*****************************
            Dim Doc_TYPE As String = "ZDR"     'CN = ZCR ใหม่น้อยกว่าเก่า , DN = ZDR  ใหม่มากกว่าเก่า
            Dim Reason As String = "Z03"   'เหตุผล  ZO1   DN, Z02  CN, Z03 Quatity Change(Target_Qty ใส่ตามจำนวนเต็ม)
            Dim REF_DOC As String = Biiling  'Billing
            'Z01 ราคาลด  ,Z02 ราคาเพิ่ม  , Z03 เปลี่ยน Quatity
            For Each dr As DataRow In dt.Rows
                CNDN_Quatity = New SAP_IPORT.ZBAPI_CN_DN_ITEMS
                CNDN_Quatity.Material = dr.Item("Material")
                CNDN_Quatity.Plant = dr.Item("Plant")
                CNDN_Quatity.Target_Qty = dr.Item("Target_Qty")
                CNDN_Quatity.Target_Qu = dr.Item("Target_Qu")
                CNDN_Quatity.Cond_Type = "ZNET"
                CNDN_Quatity.Amount = dr.Item("Amount")
                CNDN_TABLE_Quatity.Insert(0, CNDN_Quatity)
            Next

            SAP_Data.Zbapi_Iport_Sd_Cn_Dn_Request(Doc_TYPE, IPROT_NUMBER, Reason, REF_DOC, EX_Sale, CNDN_TABLE_Quatity, ZBABI_RET_Quatity)
            ClassSAP.SAP_CLOSE(SAP_Data)
            If (EX_Sale <> "") Then
                Return True
            Else
                Return False
            End If
        Catch ex As Exception
            Return False
        End Try

    End Function
    Private Sub btnSaveBookingCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSaveBookingCancel.Click
        Dim Status As String = "CC"
        Dim conn As New System.Data.SqlClient.SqlConnection(connString)
        Dim clsDB As New ClassDatabase
        Dim clsFc As New ClassFunction
        Dim condition As Boolean = True
        Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
        Dim ds_Log As DataTable = clsGet.Get_Booking_LOG(ViewState("EditBooking"))
        Dim Customer_Action As String = CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("User_name") & " " & DateTime.Now.ToString("yyyyMMdd:HHmmss")
        Dim Cancel_Description As String = Session("Cancel_Description")
        Session("Cancel_Description") = Nothing
        Dim CreateCNDN As Boolean = True
        Dim Booking_Log As String = Date.Now.ToString("yyyyMMddHHmmss")

        If (Session("Role") = "00004") Then
            Status = "CV"
        Else
            Status = "CR"
        End If
        If (clsGet.GetPaymentForCancel(ViewState("EditBooking"))) Then
            'สร้าง CNDN แล้วคืนค่าว่าสำเร็จไม่สำเร็จ

            Dim CNDN_TABLE As New SAP_IPORT.ZBAPI_CN_DN_ITEMSTable
            Dim CNDN As New SAP_IPORT.ZBAPI_CN_DN_ITEMS
            Dim ZBABI_RET As New SAP_IPORT.BAPIRET1Table
            Dim IPROT_NUMBER As String = ""
            Dim ds As New DataSet
            Dim dtSale_Order As DataTable = clsGet.Get_SaleORDER_IPort_Number(ViewState("EditBooking"), "")
            For Each dr As DataRow In dtSale_Order.Rows
                If (dr.Item("EX_BILL_NO") & "" = "") Then
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการปลดบล็อค Credit Limit ก่อนทำการยกเลิกการจอง');", True)
                    Exit Sub
                Else
                    Dim dtMat As DataTable = clsGet.Get_SaleORDER_Material(dr.Item("Iport_no"))
                    ds.Tables.Add(dtMat.Copy)
                    ds.AcceptChanges()
                End If
            Next
            Dim bill_no As String = ""
            Dim bill_to As String = ""
            Dim Old_Iport_no As String = ""
            IPROT_NUMBER = clsGet.Get_IportNumber()
            IPROT_NUMBER = IPROT_NUMBER.Substring(0, 8) & "-" & (CInt(IPROT_NUMBER.Substring(9, 3)) - 1).ToString("000")
            Dim Due_Date As String = Date.Now.AddDays(30).ToString("yyyyMMdd", New CultureInfo("en-US"))
            Dim EX_Sale As String = ""  'Sale Number
            Dim CNDNCon As Boolean = True
            Application.Lock()
            conn.Open()
            tran = clsDB.BeginTran(conn)
            For i As Integer = 0 To dtSale_Order.Rows.Count - 1
                IPROT_NUMBER = IPROT_NUMBER.Substring(0, 8) & "-" & (CInt(IPROT_NUMBER.Substring(9, 3)) + 1).ToString("000")
                bill_no = dtSale_Order.Rows(i).Item("EX_BILL_NO")
                bill_to = dtSale_Order.Rows(i).Item("Bill_To")
                Old_Iport_no = dtSale_Order.Rows(i).Item("Iport_no")
                Dim dtMat As DataTable = ds.Tables(i)
                CNDNCon = CNDN_REQUEST(IPROT_NUMBER, bill_no, Due_Date, EX_Sale, dtMat, CNDN, CNDN_TABLE, ZBABI_RET)
                If (CNDNCon = False) Then
                    CreateCNDN = False
                    If (ZBABI_RET.Count > 0) Then
                        Dim condi As Boolean = True
                        For Each dr As SAP_IPORT.BAPIRET1 In ZBABI_RET
                            If (clsFc.InsertSAP_Table_MESSAGE(IPROT_NUMBER, "Zbapi_Iport_Sd_Cn_Dn_Request", dr.Type, dr.Id, dr.Number, dr.Message, dr.Log_No, dr.Log_Msg_No, dr.Message_V1, dr.Message_V2, dr.Message_V3, dr.Message_V4, conn, tran) < 1) Then
                                condi = False
                                Exit For
                            End If
                        Next
                        If (condi) Then
                            clsDB.CommitTran(tran)
                        Else
                            clsDB.RollBackTran(tran)
                        End If
                        Application.UnLock()
                        conn.Dispose()
                        ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการเชื่อมต่อกับ SAP');", True)
                        Exit Sub
                    End If

                Else
                    If (clsFc.InsertSAP_CNDN_REQUEST(ViewState("EditBooking"), IPROT_NUMBER, bill_no, "ZDR", "Z03", Due_Date, EX_Sale, bill_to, "N", Old_Iport_no, conn, tran) > 0) Then
                        For Each dr As SAP_IPORT.ZBAPI_CN_DN_ITEMS In CNDN_TABLE
                            If (clsFc.InsertSAP_CNDN_ITEM_REQUEST(IPROT_NUMBER, dr.Material, dr.Plant, dr.Target_Qty, dr.Target_Qu, dr.Cond_Type, dr.Amount, conn, tran) < 1) Then
                                CreateCNDN = False
                                Exit For
                            End If
                        Next
                    End If
                    For Each dr As SAP_IPORT.BAPIRET1 In ZBABI_RET
                        If (clsFc.InsertSAP_Table_MESSAGE(IPROT_NUMBER, "Zbapi_Iport_Sd_Cn_Dn_Request", dr.Type, dr.Id, dr.Number, dr.Message, dr.Log_No, dr.Log_Msg_No, dr.Message_V1, dr.Message_V2, dr.Message_V3, dr.Message_V4, conn, tran) < 1) Then
                            CreateCNDN = False
                            Exit For
                        End If
                    Next
                End If
            Next
        Else
            Application.Lock()
            conn.Open()
            tran = clsDB.BeginTran(conn)
        End If
        If (CreateCNDN) Then

            Try
                If (clsFc.UpdateCancelBooking(ViewState("EditBooking"), Status, Customer_Action, Cancel_Description, "", conn, tran) > 0) Then
                    If (clsFc.InsertBooking_Log(Booking_Log, ViewState("EditBooking"), ds_Log.Rows(0).Item("Booking_Code"), ds_Log.Rows(0).Item("Booking_name"), ds_Log.Rows(0).Item("Vehicle_no"), ds_Log.Rows(0).Item("Vehicle_Text"), ds_Log.Rows(0).Item("Vehicle_LOA"), ds_Log.Rows(0).Item("Vehicle_DWT"), ds_Log.Rows(0).Item("Vehicle_Draft"), ds_Log.Rows(0).Item("Vehicle_GRT"), ds_Log.Rows(0).Item("Date_From"), ds_Log.Rows(0).Item("Date_To"), ds_Log.Rows(0).Item("PORT"), ds_Log.Rows(0).Item("Vehicle_destination"), ds_Log.Rows(0).Item("Vehicle_TypeBuy"), ds_Log.Rows(0).Item("Remark"), ds_Log.Rows(0).Item("Status"), ds_Log.Rows(0).Item("Remark_VPS"), ds_Log.Rows(0).Item("VPS_Approve"), ds_Log.Rows(0).Item("Remark_MRI"), ds_Log.Rows(0).Item("MRI_Approve"), ds_Log.Rows(0).Item("Marketing_Approve"), ds_Log.Rows(0).Item("Product_name"), ds_Log.Rows(0).Item("Product_Amount"), ds_Log.Rows(0).Item("MAgent_no"), ds_Log.Rows(0).Item("MAgent_name"), ds_Log.Rows(0).Item("SAgent_no"), ds_Log.Rows(0).Item("SAgent_name"), ds_Log.Rows(0).Item("Booking_Date"), ds_Log.Rows(0).Item("Booking_Time"), ds_Log.Rows(0).Item("Buyer"), ds_Log.Rows(0).Item("Seller"), ds_Log.Rows(0).Item("Product_Unit"), ds_Log.Rows(0).Item("File_Upload"), ds_Log.Rows(0).Item("Vehicle_CNTRY"), ds_Log.Rows(0).Item("Lay_Time"), ds_Log.Rows(0).Item("MKT_Product"), ds_Log.Rows(0).Item("MKT_Custom"), ds_Log.Rows(0).Item("MKT_Finance"), ds_Log.Rows(0).Item("BunkerFO_chk"), ds_Log.Rows(0).Item("BunkerDO_chk"), ds_Log.Rows(0).Item("BunkerFO_Point"), ds_Log.Rows(0).Item("BunkerDO_Point"), ds_Log.Rows(0).Item("BunkerDetail"), ds_Log.Rows(0).Item("Water_Point"), "", Customer_Action, Cancel_Description, "", "", ds_Log.Rows(0).Item("Payin"), ds_Log.Rows(0).Item("Bill_To_no"), ds_Log.Rows(0).Item("Bill_To_name"), ds_Log.Rows(0).Item("StandardTime"), ds_Log.Rows(0).Item("Credit_Limit"), ds_Log.Rows(0).Item("Status_Pay"), ds_Log.Rows(0).Item("Demurrage"), ds_Log.Rows(0).Item("Demurrage_Money"), ds_Log.Rows(0).Item("Electricity") & "", ds_Log.Rows(0).Item("Shifting") & "", conn, tran) < 1) Then
                        condition = False
                    End If
                End If
                If (condition) Then
                    clsDB.CommitTran(tran)
                    LoadBOoking()
                    Timer1_Tick(sender, e)
                    Dim str As String = GenBody("รายการจองได้ถูกทำการยกเลิก กรุณาทำการตรวจสอบข้อมูลผ่านระบบ iPORT", ViewState("EditBooking"), ds_Log.Rows(0).Item("MAgent_no") & "-" & ds_Log.Rows(0).Item("MAgent_name"), ds_Log.Rows(0).Item("Vehicle_no") & "-" & ds_Log.Rows(0).Item("Vehicle_Text"), ds_Log.Rows(0).Item("Date_From") & "-" & ds_Log.Rows(0).Item("Date_To"))
                    SendMail(ViewState("EditBooking"), "CANCEL", str, "")
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ทำการยกเลิกรายการจองสำเร็จ ');", True)
                Else
                    clsDB.RollBackTran(tran)
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการบันทึก');", True)
                End If
            Catch ex As Exception
                clsDB.RollBackTran(tran)
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการบันทึก');", True)
            End Try
            Application.UnLock()
            conn.Dispose()
        Else
            clsDB.RollBackTran(tran)
            Application.UnLock()
            conn.Dispose()
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการเชื่อมต่อกับ SAP');", True)
        End If
    End Sub

    Private Sub btnSaveBookingCancelMKT_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSaveBookingCancelMKT.Click
        Dim Status As String = "CM"
        Dim CreateCNDN As Boolean = True
        If (clsGet.GetPaymentForCancel(ViewState("EditBooking"))) Then
            'สร้าง CNDN แล้วคืนค่าว่าสำเร็จไม่สำเร็จ
        End If
        If (CreateCNDN) Then
            Dim conn As New System.Data.SqlClient.SqlConnection(connString)
            Dim clsDB As New ClassDatabase
            Dim clsFc As New ClassFunction
            Dim condition As Boolean = True
            Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
            Dim ds_Log As DataTable = clsGet.Get_Booking_LOG(ViewState("EditBooking"))
            Dim Customer_Action As String = CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("User_name") & " " & DateTime.Now.ToString("yyyyMMdd:HHmmss")
            Dim Cancel_Description As String = Session("Cancel_Description")
            Session("Cancel_Description") = Nothing
            Application.Lock()
            conn.Open()

            Dim Booking_Log As String = Date.Now.ToString("yyyyMMddHHmmss")
            tran = clsDB.BeginTran(conn)
            Try

                If (clsFc.UpdateCancelBooking(ViewState("EditBooking"), Status, Customer_Action, Cancel_Description, "", conn, tran) > 0) Then
                    If (clsFc.InsertBooking_Log(Booking_Log, ViewState("EditBooking"), ds_Log.Rows(0).Item("Booking_Code"), ds_Log.Rows(0).Item("Booking_name"), ds_Log.Rows(0).Item("Vehicle_no"), ds_Log.Rows(0).Item("Vehicle_Text"), ds_Log.Rows(0).Item("Vehicle_LOA"), ds_Log.Rows(0).Item("Vehicle_DWT"), ds_Log.Rows(0).Item("Vehicle_Draft"), ds_Log.Rows(0).Item("Vehicle_GRT"), ds_Log.Rows(0).Item("Date_From"), ds_Log.Rows(0).Item("Date_To"), ds_Log.Rows(0).Item("PORT"), ds_Log.Rows(0).Item("Vehicle_destination"), ds_Log.Rows(0).Item("Vehicle_TypeBuy"), ds_Log.Rows(0).Item("Remark"), ds_Log.Rows(0).Item("Status"), ds_Log.Rows(0).Item("Remark_VPS"), ds_Log.Rows(0).Item("VPS_Approve"), ds_Log.Rows(0).Item("Remark_MRI"), ds_Log.Rows(0).Item("MRI_Approve"), ds_Log.Rows(0).Item("Marketing_Approve"), ds_Log.Rows(0).Item("Product_name"), ds_Log.Rows(0).Item("Product_Amount"), ds_Log.Rows(0).Item("MAgent_no"), ds_Log.Rows(0).Item("MAgent_name"), ds_Log.Rows(0).Item("SAgent_no"), ds_Log.Rows(0).Item("SAgent_name"), ds_Log.Rows(0).Item("Booking_Date"), ds_Log.Rows(0).Item("Booking_Time"), ds_Log.Rows(0).Item("Buyer"), ds_Log.Rows(0).Item("Seller"), ds_Log.Rows(0).Item("Product_Unit"), ds_Log.Rows(0).Item("File_Upload"), ds_Log.Rows(0).Item("Vehicle_CNTRY"), ds_Log.Rows(0).Item("Lay_Time"), ds_Log.Rows(0).Item("MKT_Product"), ds_Log.Rows(0).Item("MKT_Custom"), ds_Log.Rows(0).Item("MKT_Finance"), ds_Log.Rows(0).Item("BunkerFO_chk"), ds_Log.Rows(0).Item("BunkerDO_chk"), ds_Log.Rows(0).Item("BunkerFO_Point"), ds_Log.Rows(0).Item("BunkerDO_Point"), ds_Log.Rows(0).Item("BunkerDetail"), ds_Log.Rows(0).Item("Water_Point"), "", Customer_Action, Cancel_Description, "", "", ds_Log.Rows(0).Item("Payin"), ds_Log.Rows(0).Item("Bill_To_no"), ds_Log.Rows(0).Item("Bill_To_name"), ds_Log.Rows(0).Item("StandardTime"), ds_Log.Rows(0).Item("Credit_Limit"), ds_Log.Rows(0).Item("Status_Pay"), ds_Log.Rows(0).Item("Demurrage"), ds_Log.Rows(0).Item("Demurrage_Money"), ds_Log.Rows(0).Item("Electricity") & "", ds_Log.Rows(0).Item("Shifting") & "", conn, tran) < 1) Then
                        condition = False
                    End If
                End If
                If (condition) Then
                    clsDB.CommitTran(tran)
                    LoadBOoking()
                    Timer1_Tick(sender, e)
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ทำการยกเลิกรายการจองสำเร็จ ');", True)
                Else
                    clsDB.RollBackTran(tran)
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการบันทึก');", True)
                End If
            Catch ex As Exception
                clsDB.RollBackTran(tran)
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการบันทึก');", True)
            End Try
            Application.UnLock()
            conn.Dispose()
        Else
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการเชื่อมต่อกับ SAP');", True)
        End If

    End Sub

    Private Sub btnBackCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnBackCancel.Click
        LoadBOoking()
        Timer1_Tick(sender, e)
    End Sub

    Private Sub btnAcknowledge_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAcknowledge.Click
        Dim conn As New System.Data.SqlClient.SqlConnection(connString)
        Dim clsDB As New ClassDatabase
        Dim clsFc As New ClassFunction
        Dim condition As Boolean = True
        Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
        Dim ds_Log As DataTable = clsGet.Get_Booking_LOG(ViewState("EditBooking"))
        Dim Customer_Action As String = CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("User_name") & " " & DateTime.Now.ToString("yyyyMMdd:HHmmss")
        Dim Cancel_Description As String = Session("Cancel_Description")
        Session("Cancel_Description") = Nothing
        Application.Lock()
        conn.Open()

        Dim Booking_Log As String = Date.Now.ToString("yyyyMMddHHmmss")
        tran = clsDB.BeginTran(conn)
        Try
            If (Session("Role") & "" = "00004") Then
                'VPS
                If (clsFc.UpdateCancelVps_Acknowledge(ViewState("EditBooking"), Customer_Action, conn, tran) > 0) Then
                    If (clsFc.InsertBooking_Log(Booking_Log, ViewState("EditBooking"), ds_Log.Rows(0).Item("Booking_Code"), ds_Log.Rows(0).Item("Booking_name"), ds_Log.Rows(0).Item("Vehicle_no"), ds_Log.Rows(0).Item("Vehicle_Text"), ds_Log.Rows(0).Item("Vehicle_LOA"), ds_Log.Rows(0).Item("Vehicle_DWT"), ds_Log.Rows(0).Item("Vehicle_Draft"), ds_Log.Rows(0).Item("Vehicle_GRT"), ds_Log.Rows(0).Item("Date_From"), ds_Log.Rows(0).Item("Date_To"), ds_Log.Rows(0).Item("PORT"), ds_Log.Rows(0).Item("Vehicle_destination"), ds_Log.Rows(0).Item("Vehicle_TypeBuy"), ds_Log.Rows(0).Item("Remark"), ds_Log.Rows(0).Item("Status"), ds_Log.Rows(0).Item("Remark_VPS"), ds_Log.Rows(0).Item("VPS_Approve"), ds_Log.Rows(0).Item("Remark_MRI"), ds_Log.Rows(0).Item("MRI_Approve"), ds_Log.Rows(0).Item("Marketing_Approve"), ds_Log.Rows(0).Item("Product_name"), ds_Log.Rows(0).Item("Product_Amount"), ds_Log.Rows(0).Item("MAgent_no"), ds_Log.Rows(0).Item("MAgent_name"), ds_Log.Rows(0).Item("SAgent_no"), ds_Log.Rows(0).Item("SAgent_name"), ds_Log.Rows(0).Item("Booking_Date"), ds_Log.Rows(0).Item("Booking_Time"), ds_Log.Rows(0).Item("Buyer"), ds_Log.Rows(0).Item("Seller"), ds_Log.Rows(0).Item("Product_Unit"), ds_Log.Rows(0).Item("File_Upload"), ds_Log.Rows(0).Item("Vehicle_CNTRY"), ds_Log.Rows(0).Item("Lay_Time"), ds_Log.Rows(0).Item("MKT_Product"), ds_Log.Rows(0).Item("MKT_Custom"), ds_Log.Rows(0).Item("MKT_Finance"), ds_Log.Rows(0).Item("BunkerFO_chk"), ds_Log.Rows(0).Item("BunkerDO_chk"), ds_Log.Rows(0).Item("BunkerFO_Point"), ds_Log.Rows(0).Item("BunkerDO_Point"), ds_Log.Rows(0).Item("BunkerDetail"), ds_Log.Rows(0).Item("Water_Point"), "", ds_Log.Rows(0).Item("Cancel_By"), ds_Log.Rows(0).Item("Cancel_Description"), Customer_Action, ds_Log.Rows(0).Item("MKT_Acknowledge"), ds_Log.Rows(0).Item("Payin"), ds_Log.Rows(0).Item("Bill_To_no"), ds_Log.Rows(0).Item("Bill_To_name"), ds_Log.Rows(0).Item("StandardTime"), ds_Log.Rows(0).Item("Credit_Limit"), ds_Log.Rows(0).Item("Status_Pay"), ds_Log.Rows(0).Item("Demurrage"), ds_Log.Rows(0).Item("Demurrage_Money"), ds_Log.Rows(0).Item("Electricity") & "", ds_Log.Rows(0).Item("Shifting") & "", conn, tran) < 1) Then
                        condition = False
                    End If
                End If
            Else
                'Marketing
                If (clsFc.UpdateCancelMKT_Acknowledge(ViewState("EditBooking"), Customer_Action, conn, tran) > 0) Then
                    If (clsFc.InsertBooking_Log(Booking_Log, ViewState("EditBooking"), ds_Log.Rows(0).Item("Booking_Code"), ds_Log.Rows(0).Item("Booking_name"), ds_Log.Rows(0).Item("Vehicle_no"), ds_Log.Rows(0).Item("Vehicle_Text"), ds_Log.Rows(0).Item("Vehicle_LOA"), ds_Log.Rows(0).Item("Vehicle_DWT"), ds_Log.Rows(0).Item("Vehicle_Draft"), ds_Log.Rows(0).Item("Vehicle_GRT"), ds_Log.Rows(0).Item("Date_From"), ds_Log.Rows(0).Item("Date_To"), ds_Log.Rows(0).Item("PORT"), ds_Log.Rows(0).Item("Vehicle_destination"), ds_Log.Rows(0).Item("Vehicle_TypeBuy"), ds_Log.Rows(0).Item("Remark"), ds_Log.Rows(0).Item("Status"), ds_Log.Rows(0).Item("Remark_VPS"), ds_Log.Rows(0).Item("VPS_Approve"), ds_Log.Rows(0).Item("Remark_MRI"), ds_Log.Rows(0).Item("MRI_Approve"), ds_Log.Rows(0).Item("Marketing_Approve"), ds_Log.Rows(0).Item("Product_name"), ds_Log.Rows(0).Item("Product_Amount"), ds_Log.Rows(0).Item("MAgent_no"), ds_Log.Rows(0).Item("MAgent_name"), ds_Log.Rows(0).Item("SAgent_no"), ds_Log.Rows(0).Item("SAgent_name"), ds_Log.Rows(0).Item("Booking_Date"), ds_Log.Rows(0).Item("Booking_Time"), ds_Log.Rows(0).Item("Buyer"), ds_Log.Rows(0).Item("Seller"), ds_Log.Rows(0).Item("Product_Unit"), ds_Log.Rows(0).Item("File_Upload"), ds_Log.Rows(0).Item("Vehicle_CNTRY"), ds_Log.Rows(0).Item("Lay_Time"), ds_Log.Rows(0).Item("MKT_Product"), ds_Log.Rows(0).Item("MKT_Custom"), ds_Log.Rows(0).Item("MKT_Finance"), ds_Log.Rows(0).Item("BunkerFO_chk"), ds_Log.Rows(0).Item("BunkerDO_chk"), ds_Log.Rows(0).Item("BunkerFO_Point"), ds_Log.Rows(0).Item("BunkerDO_Point"), ds_Log.Rows(0).Item("BunkerDetail"), ds_Log.Rows(0).Item("Water_Point"), "", ds_Log.Rows(0).Item("Cancel_By"), ds_Log.Rows(0).Item("Cancel_Description"), ds_Log.Rows(0).Item("Vps_Acknowledge"), Customer_Action, ds_Log.Rows(0).Item("Payin"), ds_Log.Rows(0).Item("Bill_To_no"), ds_Log.Rows(0).Item("Bill_To_name"), ds_Log.Rows(0).Item("StandardTime"), ds_Log.Rows(0).Item("Credit_Limit"), ds_Log.Rows(0).Item("Status_Pay"), ds_Log.Rows(0).Item("Demurrage"), ds_Log.Rows(0).Item("Demurrage_Money"), ds_Log.Rows(0).Item("Electricity") & "", ds_Log.Rows(0).Item("Shifting") & "", conn, tran) < 1) Then
                        condition = False
                    End If
                End If
            End If

            If (condition) Then
                clsDB.CommitTran(tran)
                LoadBOoking()
                Timer1_Tick(sender, e)
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('รับทราบการขอยกเลิกรายการจองแล้ว ');", True)
            Else
                clsDB.RollBackTran(tran)
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการบันทึก');", True)
            End If
        Catch ex As Exception
            clsDB.RollBackTran(tran)
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการบันทึก');", True)
        End Try
        Application.UnLock()
        conn.Dispose()
    End Sub

    Private Sub btnCancelByCustomer_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancelByCustomer.Click
        Dim Status As String = "CA"
        Dim conn As New System.Data.SqlClient.SqlConnection(connString)
        Dim clsDB As New ClassDatabase
        Dim clsFc As New ClassFunction
        Dim condition As Boolean = True
        Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
        Dim ds_Log As DataTable = clsGet.Get_Booking_LOG(ViewState("EditBooking"))
        Dim Customer_Action As String = CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("User_name") & " " & DateTime.Now.ToString("yyyyMMdd:HHmmss")
        Application.Lock()
        conn.Open()

        Dim Booking_Log As String = Date.Now.ToString("yyyyMMddHHmmss")
        tran = clsDB.BeginTran(conn)
        Try
            If (clsFc.UpdateCancelBooking(ViewState("EditBooking"), Status, "", "", Customer_Action, conn, tran) > 0) Then
                If (clsFc.InsertBooking_Log(Booking_Log, ViewState("EditBooking"), ds_Log.Rows(0).Item("Booking_Code"), ds_Log.Rows(0).Item("Booking_name"), ds_Log.Rows(0).Item("Vehicle_no"), ds_Log.Rows(0).Item("Vehicle_Text"), ds_Log.Rows(0).Item("Vehicle_LOA"), ds_Log.Rows(0).Item("Vehicle_DWT"), ds_Log.Rows(0).Item("Vehicle_Draft"), ds_Log.Rows(0).Item("Vehicle_GRT"), ds_Log.Rows(0).Item("Date_From"), ds_Log.Rows(0).Item("Date_To"), ds_Log.Rows(0).Item("PORT"), ds_Log.Rows(0).Item("Vehicle_destination"), ds_Log.Rows(0).Item("Vehicle_TypeBuy"), ds_Log.Rows(0).Item("Remark"), ds_Log.Rows(0).Item("Status"), ds_Log.Rows(0).Item("Remark_VPS"), ds_Log.Rows(0).Item("VPS_Approve"), ds_Log.Rows(0).Item("Remark_MRI"), ds_Log.Rows(0).Item("MRI_Approve"), ds_Log.Rows(0).Item("Marketing_Approve"), ds_Log.Rows(0).Item("Product_name"), ds_Log.Rows(0).Item("Product_Amount"), ds_Log.Rows(0).Item("MAgent_no"), ds_Log.Rows(0).Item("MAgent_name"), ds_Log.Rows(0).Item("SAgent_no"), ds_Log.Rows(0).Item("SAgent_name"), ds_Log.Rows(0).Item("Booking_Date"), ds_Log.Rows(0).Item("Booking_Time"), ds_Log.Rows(0).Item("Buyer"), ds_Log.Rows(0).Item("Seller"), ds_Log.Rows(0).Item("Product_Unit"), ds_Log.Rows(0).Item("File_Upload"), ds_Log.Rows(0).Item("Vehicle_CNTRY"), ds_Log.Rows(0).Item("Lay_Time"), ds_Log.Rows(0).Item("MKT_Product"), ds_Log.Rows(0).Item("MKT_Custom"), ds_Log.Rows(0).Item("MKT_Finance"), ds_Log.Rows(0).Item("BunkerFO_chk"), ds_Log.Rows(0).Item("BunkerDO_chk"), ds_Log.Rows(0).Item("BunkerFO_Point"), ds_Log.Rows(0).Item("BunkerDO_Point"), ds_Log.Rows(0).Item("BunkerDetail"), ds_Log.Rows(0).Item("Water_Point"), "", ds_Log.Rows(0).Item("Cancel_By"), ds_Log.Rows(0).Item("Cancel_Description"), "", "", ds_Log.Rows(0).Item("Payin"), ds_Log.Rows(0).Item("Bill_To_no"), ds_Log.Rows(0).Item("Bill_To_name"), ds_Log.Rows(0).Item("StandardTime"), ds_Log.Rows(0).Item("Credit_Limit"), ds_Log.Rows(0).Item("Status_Pay"), ds_Log.Rows(0).Item("Demurrage"), ds_Log.Rows(0).Item("Demurrage_Money"), ds_Log.Rows(0).Item("Electricity") & "", ds_Log.Rows(0).Item("Shifting") & "", conn, tran) < 1) Then
                    condition = False
                End If
            End If
            If (condition) Then
                clsDB.CommitTran(tran)
                LoadBOoking()
                Timer1_Tick(sender, e)
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ทำการยกเลิกรายการจองสำเร็จ ');", True)
            Else
                clsDB.RollBackTran(tran)
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการบันทึก');", True)
            End If
        Catch ex As Exception
            clsDB.RollBackTran(tran)
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการบันทึก');", True)
        End Try
        Application.UnLock()
        conn.Dispose()
    End Sub

    Private Function Create_Credit_Sale(ByVal Booking_no As String, ByVal VPS As String, ByVal Status As String, ByVal Bill_to_no As String, ByVal Bill_to_name As String, ByRef conditionMaster As Boolean) As Boolean
        Try
            Dim clsDB As New ClassDatabase()

            Dim SoldTo As String = ""
            Dim BillTo As String = ""
            Dim Bill_Date As String = Date.Now.ToString("yyyyMMdd", New CultureInfo("en-US"))

            Dim ClassSAP As New Class_SAP
            Dim SAP_Data As Object = ClassSAP.SAP_OPEN()
            Dim ds As DataTable = clsGet.Get_MatFor_Sale_Order(Booking_no, "")
            Dim chkcredit As String = True   'Check True = ผ่าน , Check False = ติดเครติด
            Dim dssale_Order As DataTable = clsGet.GetRowForSaleOrder(ds)
            Dim Iport_Number As String = clsGet.Get_IportNumber()
            Iport_Number = Iport_Number.Substring(0, 8) & "-" & (CInt(Iport_Number.Substring(9, 3)) - 1).ToString("000")
            Dim Owner_Product As String = ""
            For Each drx As DataRow In dssale_Order.Rows
                If (drx.Item("sold_to") = "Not") Then
                    SoldTo = txtid.Text.Split("-")(0)
                    If (txtBillTo.Text.Trim() = "") Then
                        BillTo = SoldTo
                    Else
                        BillTo = txtBillTo.Text.Split("-")(0)
                    End If
                Else
                    SoldTo = drx.Item("sold_to")
                    BillTo = drx.Item("sold_to")
                End If
                Owner_Product = drx.Item("sold_to")
                Dim BABIONETIME11 As New SAP_IPORT.ZBAPI_SALES_ONETIME

                Dim EX_SALES_NO11 As String = ""
                Dim EX_BILL_NO11 As String = ""

                Dim BABIONETIME12 As New SAP_IPORT.ZBAPI_SALES_ONETIME
                Dim BABI_SALE11 As New SAP_IPORT.ZBAPI_SALES_ITEMS
                Dim BABI_SALE12 As New SAP_IPORT.ZBAPI_SALES_ITEMS

                Dim SALE_TABLE11_0 As New SAP_IPORT.ZBAPI_SALES_ITEMSTable
                Dim SALE_TABLE11_1 As New SAP_IPORT.ZBAPI_SALES_ITEMSTable
                Dim SALE_TABLE11_5 As New SAP_IPORT.ZBAPI_SALES_ITEMSTable


                Dim SALE_TABLE12_0 As New SAP_IPORT.ZBAPI_SALES_ITEMSTable
                Dim SALE_TABLE12_1 As New SAP_IPORT.ZBAPI_SALES_ITEMSTable
                Dim SALE_TABLE12_5 As New SAP_IPORT.ZBAPI_SALES_ITEMSTable

                Dim BABITable11 As New SAP_IPORT.BAPIRET1Table
                Dim BABITable12 As New SAP_IPORT.BAPIRET1Table

                Dim EX_SALES_NO12 As String = ""
                Dim EX_BILL_NO12 As String = ""

                Dim BABIHEADER11 As New SAP_IPORT.ZBAPI_SALES_HEADER
                BABIHEADER11.Doc_Type = "ZSRR"
                BABIHEADER11.Req_Date_H = Date.Now.ToString("yyyyMMdd", New CultureInfo("en-US")) ' "20100921" 
                BABIHEADER11.Sold_To = SoldTo
                BABIHEADER11.Bill_To = BillTo
                BABIHEADER11.Ship_Name = lbVehicle.Text.Split("-")(1)
                BABIHEADER11.Division = "11"

                Dim BABIHEADER12 As New SAP_IPORT.ZBAPI_SALES_HEADER
                BABIHEADER12.Doc_Type = "ZSRR"
                BABIHEADER12.Req_Date_H = Date.Now.ToString("yyyyMMdd", New CultureInfo("en-US")) ' "20100921" 
                BABIHEADER12.Sold_To = SoldTo
                BABIHEADER12.Bill_To = BillTo
                BABIHEADER12.Ship_Name = lbVehicle.Text.Split("-")(1)
                BABIHEADER12.Division = "12"

                Dim Plant As String = "1104"
                If (lbPort.Text = "Liquid") Then
                    Plant = "1103"
                End If
                Dim condition11 As Boolean = False
                Dim condition12 As Boolean = False
                For Each dr As DataRow In ds.Rows
                    'Issue  ถ้ากรณีสร้าง Sale Order มากกว่า 1 ใบ กรณีของเจ้าของสินค้าติด cradit limit ทางพี่อ้อยทำยังไง
                    'Issue  มีกรณี shipting กับ litering ที่ Job ไม่เท่ากับ 1
                    If (dr.Item("Owner_Product") = Owner_Product) Then
                        If (CInt(dr.Item("data4")) > 0) Then
                            Dim Target_QU As String = dr.Item("BASE_UOM")
                            Dim Target_Qty As String = ""
                            Dim Amount As String = ""
                            If (Target_QU = "JOB") Then
                                Target_Qty = "1"
                                Amount = dr.Item("data4")
                            Else
                                Target_Qty = (CDbl(dr.Item("data4")) / CDbl(dr.Item("data2"))).ToString()
                                Amount = dr.Item("data2")
                            End If
                            If (dr.Item("Division") & "" = "11") Then
                                BABI_SALE11 = New SAP_IPORT.ZBAPI_SALES_ITEMS
                                BABI_SALE11.Material = dr.Item("Material")
                                BABI_SALE11.Plant = Plant
                                BABI_SALE11.Target_Qty = Target_Qty
                                BABI_SALE11.Target_Qu = Target_QU
                                BABI_SALE11.Cond_Type = ""
                                BABI_SALE11.Discount = "0"
                                Try
                                    Dim dtLowRate As DataTable = clsGet.Get_ROWRATE_MAT(dr.Item("Material"))
                                    Dim LowRate As Double = "0"
                                    Dim chkROw As Boolean = False
                                    For Each dL As DataRow In dtLowRate.Rows
                                        If (CDbl(dr.Item("data4")) = CDbl(dL.Item("LowRate"))) Then
                                            LowRate = dr.Item("data4")
                                            chkROw = True
                                            Exit For
                                        End If
                                    Next
                                    If (chkROw) Then
                                        BABI_SALE11.Amount = LowRate
                                        BABI_SALE11.Condvalue = LowRate
                                    Else
                                        BABI_SALE11.Amount = Amount
                                        BABI_SALE11.Condvalue = "0"
                                    End If
                                Catch ex As Exception
                                    BABI_SALE11.Amount = Amount
                                    BABI_SALE11.Condvalue = "0"
                                End Try

                                If (dr.Item("TAXCLASS") & "" = "0") Then
                                    SALE_TABLE11_0.Insert(0, BABI_SALE11)
                                ElseIf (dr.Item("TAXCLASS") & "" = "1") Then
                                    SALE_TABLE11_1.Insert(0, BABI_SALE11)
                                ElseIf (dr.Item("TAXCLASS") & "" = "5") Then
                                    SALE_TABLE11_5.Insert(0, BABI_SALE11)
                                End If
                                condition11 = True
                            ElseIf (dr.Item("Division") & "" = "12") Then
                                BABI_SALE12 = New SAP_IPORT.ZBAPI_SALES_ITEMS
                                BABI_SALE12.Material = dr.Item("Material")
                                BABI_SALE12.Plant = Plant
                                BABI_SALE12.Target_Qty = Target_Qty
                                BABI_SALE12.Target_Qu = Target_QU
                                BABI_SALE12.Cond_Type = ""
                                BABI_SALE12.Discount = "0"
                                Try
                                    Dim dtLowRate As DataTable = clsGet.Get_ROWRATE_MAT(dr.Item("Material"))
                                    Dim LowRate As Double = "0"
                                    Dim chkROw As Boolean = False
                                    For Each dL As DataRow In dtLowRate.Rows
                                        If (CDbl(dr.Item("data4")) = CDbl(dL.Item("LowRate"))) Then
                                            LowRate = dr.Item("data4")
                                            chkROw = True
                                            Exit For
                                        End If
                                    Next
                                    If (chkROw) Then
                                        BABI_SALE12.Amount = LowRate
                                        BABI_SALE12.Condvalue = LowRate
                                    Else
                                        BABI_SALE12.Amount = Amount
                                        BABI_SALE12.Condvalue = "0"
                                    End If
                                Catch ex As Exception
                                    BABI_SALE12.Amount = Amount
                                    BABI_SALE12.Condvalue = "0"
                                End Try

                                If (dr.Item("TAXCLASS") & "" = "0") Then
                                    SALE_TABLE12_0.Insert(0, BABI_SALE12)
                                ElseIf (dr.Item("TAXCLASS") & "" = "1") Then
                                    SALE_TABLE12_1.Insert(0, BABI_SALE12)
                                ElseIf (dr.Item("TAXCLASS") & "" = "5") Then
                                    SALE_TABLE12_5.Insert(0, BABI_SALE12)
                                End If
                                condition12 = True
                            End If
                        End If

                    End If
                Next
                If (condition11) Then
                    If (SALE_TABLE11_0.Count > 0) Then
                        Iport_Number = Iport_Number.Substring(0, 8) & "-" & (CInt(Iport_Number.Substring(9, 3)) + 1).ToString("000")
                        SAP_Data.Zbapi_Iport_Sd_Proc_Cr_Sales(Bill_Date, "X", Iport_Number, BABIONETIME11, BABIHEADER11, EX_BILL_NO11, EX_SALES_NO11, BABITable11, SALE_TABLE11_0)

                        Dim conn As New System.Data.SqlClient.SqlConnection(connString)
                        Dim condition As Boolean = True
                        Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
                        Try
                            conn.Open()
                            tran = clsDB.BeginTran(conn)

                            If (clsFc.InsertIportNumber(Iport_Number, conn, tran) > 0) Then
                                For Each dr As SAP_IPORT.BAPIRET1 In BABITable11
                                    If (dr.Type = "E") And (dr.Id = "VF") And (dr.Number = "140") Then
                                        chkcredit = False
                                    End If
                                    If (clsFc.InsertSAP_Table_MESSAGE(Iport_Number, "Zbapi_Iport_Sd_Proc_Cr_Sales", dr.Type, dr.Id, dr.Number, dr.Message, dr.Log_No, dr.Log_Msg_No, dr.Message_V1, dr.Message_V2, dr.Message_V3, dr.Message_V4, conn, tran) < 1) Then
                                        condition = False
                                    End If
                                Next
                                If (condition) Then
                                    Dim Credit_limit As String = ""
                                    If (chkcredit) Then
                                        Credit_limit = "Y"
                                    Else
                                        Credit_limit = "N"
                                    End If
                                    If (clsFc.InsertSaleOrder(Booking_no, Iport_Number, BABIHEADER11.Doc_Type, BABIHEADER11.Req_Date_H, BABIHEADER11.Sold_To, BABIHEADER11.Bill_To, BABIHEADER11.Ship_Name, BABIHEADER11.Division, EX_SALES_NO11, EX_BILL_NO11, Credit_limit, "", "", "", Bill_Date, conn, tran) > 0) Then
                                        For Each dr As SAP_IPORT.ZBAPI_SALES_ITEMS In SALE_TABLE11_0
                                            If (dr.Material <> "") Then
                                                If (clsFc.InsertSAP_Sale_Order_Material(Iport_Number, dr.Material, dr.Plant, dr.Target_Qty, dr.Target_Qu, dr.Cond_Type, dr.Discount, dr.Amount, dr.Condvalue, conn, tran) < 1) Then
                                                    condition = False
                                                End If
                                            End If
                                        Next
                                    Else
                                        condition = False
                                    End If

                                End If
                            Else
                                condition = False
                            End If

                            If (condition) Then
                                clsDB.CommitTran(tran)
                            Else
                                clsDB.RollBackTran(tran)
                                conditionMaster = False
                            End If

                        Catch ex As Exception
                            clsDB.RollBackTran(tran)
                            conditionMaster = False
                        End Try
                        conn.Dispose()
                    End If
                    If (SALE_TABLE11_1.Count > 0) Then
                        Iport_Number = Iport_Number.Substring(0, 8) & "-" & (CInt(Iport_Number.Substring(9, 3)) + 1).ToString("000")
                        SAP_Data.Zbapi_Iport_Sd_Proc_Cr_Sales(Bill_Date, "X", Iport_Number, BABIONETIME11, BABIHEADER11, EX_BILL_NO11, EX_SALES_NO11, BABITable11, SALE_TABLE11_1)

                        Dim conn As New System.Data.SqlClient.SqlConnection(connString)
                        Dim condition As Boolean = True
                        Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
                        Try
                            conn.Open()
                            tran = clsDB.BeginTran(conn)

                            If (clsFc.InsertIportNumber(Iport_Number, conn, tran) > 0) Then
                                For Each dr As SAP_IPORT.BAPIRET1 In BABITable11
                                    If (dr.Type = "E") And (dr.Id = "VF") And (dr.Number = "140") Then
                                        chkcredit = False
                                    End If
                                    If (clsFc.InsertSAP_Table_MESSAGE(Iport_Number, "Zbapi_Iport_Sd_Proc_Cr_Sales", dr.Type, dr.Id, dr.Number, dr.Message, dr.Log_No, dr.Log_Msg_No, dr.Message_V1, dr.Message_V2, dr.Message_V3, dr.Message_V4, conn, tran) < 1) Then
                                        condition = False
                                    End If
                                Next
                                If (condition) Then
                                    Dim Credit_limit As String = ""
                                    If (chkcredit) Then
                                        Credit_limit = "Y"
                                    Else
                                        Credit_limit = "N"
                                    End If
                                    If (clsFc.InsertSaleOrder(Booking_no, Iport_Number, BABIHEADER11.Doc_Type, BABIHEADER11.Req_Date_H, BABIHEADER11.Sold_To, BABIHEADER11.Bill_To, BABIHEADER11.Ship_Name, BABIHEADER11.Division, EX_SALES_NO11, EX_BILL_NO11, Credit_limit, "", "", "", Bill_Date, conn, tran) > 0) Then
                                        For Each dr As SAP_IPORT.ZBAPI_SALES_ITEMS In SALE_TABLE11_1
                                            If (dr.Material <> "") Then
                                                If (clsFc.InsertSAP_Sale_Order_Material(Iport_Number, dr.Material, dr.Plant, dr.Target_Qty, dr.Target_Qu, dr.Cond_Type, dr.Discount, dr.Amount, dr.Condvalue, conn, tran) < 1) Then
                                                    condition = False
                                                End If
                                            End If
                                        Next
                                    Else
                                        condition = False
                                    End If

                                End If
                            Else
                                condition = False
                            End If

                            If (condition) Then
                                clsDB.CommitTran(tran)
                            Else
                                clsDB.RollBackTran(tran)
                                conditionMaster = False
                            End If

                        Catch ex As Exception
                            clsDB.RollBackTran(tran)
                            conditionMaster = False
                        End Try
                        conn.Dispose()
                    End If
                    If (SALE_TABLE11_5.Count > 0) Then
                        Iport_Number = Iport_Number.Substring(0, 8) & "-" & (CInt(Iport_Number.Substring(9, 3)) + 1).ToString("000")
                        SAP_Data.Zbapi_Iport_Sd_Proc_Cr_Sales(Bill_Date, "X", Iport_Number, BABIONETIME11, BABIHEADER11, EX_BILL_NO11, EX_SALES_NO11, BABITable11, SALE_TABLE11_5)

                        Dim conn As New System.Data.SqlClient.SqlConnection(connString)
                        Dim condition As Boolean = True
                        Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
                        Try
                            conn.Open()
                            tran = clsDB.BeginTran(conn)

                            If (clsFc.InsertIportNumber(Iport_Number, conn, tran) > 0) Then
                                For Each dr As SAP_IPORT.BAPIRET1 In BABITable11
                                    If (dr.Type = "E") And (dr.Id = "VF") And (dr.Number = "140") Then
                                        chkcredit = False
                                    End If
                                    If (clsFc.InsertSAP_Table_MESSAGE(Iport_Number, "Zbapi_Iport_Sd_Proc_Cr_Sales", dr.Type, dr.Id, dr.Number, dr.Message, dr.Log_No, dr.Log_Msg_No, dr.Message_V1, dr.Message_V2, dr.Message_V3, dr.Message_V4, conn, tran) < 1) Then
                                        condition = False
                                    End If
                                Next
                                If (condition) Then
                                    Dim Credit_limit As String = ""
                                    If (chkcredit) Then
                                        Credit_limit = "Y"
                                    Else
                                        Credit_limit = "N"
                                    End If
                                    If (clsFc.InsertSaleOrder(Booking_no, Iport_Number, BABIHEADER11.Doc_Type, BABIHEADER11.Req_Date_H, BABIHEADER11.Sold_To, BABIHEADER11.Bill_To, BABIHEADER11.Ship_Name, BABIHEADER11.Division, EX_SALES_NO11, EX_BILL_NO11, Credit_limit, "", "", "", Bill_Date, conn, tran) > 0) Then
                                        For Each dr As SAP_IPORT.ZBAPI_SALES_ITEMS In SALE_TABLE11_5
                                            If (dr.Material <> "") Then
                                                If (clsFc.InsertSAP_Sale_Order_Material(Iport_Number, dr.Material, dr.Plant, dr.Target_Qty, dr.Target_Qu, dr.Cond_Type, dr.Discount, dr.Amount, dr.Condvalue, conn, tran) < 1) Then
                                                    condition = False
                                                End If
                                            End If
                                        Next
                                    Else
                                        condition = False
                                    End If

                                End If
                            Else
                                condition = False
                            End If

                            If (condition) Then
                                clsDB.CommitTran(tran)
                            Else
                                clsDB.RollBackTran(tran)
                                conditionMaster = False
                            End If

                        Catch ex As Exception
                            clsDB.RollBackTran(tran)
                            conditionMaster = False
                        End Try
                        conn.Dispose()
                    End If
                End If
                If (condition12) Then
                    If SALE_TABLE12_0.Count > 0 Then
                        Iport_Number = Iport_Number.Substring(0, 8) & "-" & (CInt(Iport_Number.Substring(9, 3)) + 1).ToString("000")
                        SAP_Data.Zbapi_Iport_Sd_Proc_Cr_Sales(Bill_Date, "X", Iport_Number, BABIONETIME12, BABIHEADER12, EX_BILL_NO12, EX_SALES_NO12, BABITable12, SALE_TABLE12_0)

                        Dim conn As New System.Data.SqlClient.SqlConnection(connString)
                        Dim condition As Boolean = True
                        Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
                        Try
                            conn.Open()
                            tran = clsDB.BeginTran(conn)

                            If (clsFc.InsertIportNumber(Iport_Number, conn, tran) > 0) Then
                                For Each dr As SAP_IPORT.BAPIRET1 In BABITable12
                                    If (dr.Type = "E") And (dr.Id = "VF") And (dr.Number = "140") Then
                                        chkcredit = False
                                    End If
                                    If (clsFc.InsertSAP_Table_MESSAGE(Iport_Number, "Zbapi_Iport_Sd_Proc_Cr_Sales", dr.Type, dr.Id, dr.Number, dr.Message, dr.Log_No, dr.Log_Msg_No, dr.Message_V1, dr.Message_V2, dr.Message_V3, dr.Message_V4, conn, tran) < 1) Then
                                        condition = False
                                    End If
                                Next

                                If (condition) Then
                                    Dim Credit_limit As String = ""
                                    If (chkcredit) Then
                                        Credit_limit = "Y"
                                    Else
                                        Credit_limit = "N"
                                    End If
                                    If (clsFc.InsertSaleOrder(Booking_no, Iport_Number, BABIHEADER12.Doc_Type, BABIHEADER12.Req_Date_H, BABIHEADER12.Sold_To, BABIHEADER12.Bill_To, BABIHEADER12.Ship_Name, BABIHEADER12.Division, EX_SALES_NO12, EX_BILL_NO12, Credit_limit, "", "", "", Bill_Date, conn, tran) > 0) Then
                                        For Each dr As SAP_IPORT.ZBAPI_SALES_ITEMS In SALE_TABLE12_0
                                            If (dr.Material <> "") Then
                                                If (clsFc.InsertSAP_Sale_Order_Material(Iport_Number, dr.Material, dr.Plant, dr.Target_Qty, dr.Target_Qu, dr.Cond_Type, dr.Discount, dr.Amount, dr.Condvalue, conn, tran) < 1) Then
                                                    condition = False
                                                End If
                                            End If
                                        Next
                                    Else
                                        condition = False
                                    End If
                                Else
                                    condition = False
                                End If
                            Else
                                condition = False
                            End If

                            If (condition) Then
                                clsDB.CommitTran(tran)
                            Else
                                clsDB.RollBackTran(tran)
                                conditionMaster = False
                            End If

                        Catch ex As Exception
                            clsDB.RollBackTran(tran)
                            conditionMaster = False
                        End Try
                        conn.Dispose()
                    End If
                    If SALE_TABLE12_1.Count > 0 Then
                        Iport_Number = Iport_Number.Substring(0, 8) & "-" & (CInt(Iport_Number.Substring(9, 3)) + 1).ToString("000")
                        SAP_Data.Zbapi_Iport_Sd_Proc_Cr_Sales(Bill_Date, "X", Iport_Number, BABIONETIME12, BABIHEADER12, EX_BILL_NO12, EX_SALES_NO12, BABITable12, SALE_TABLE12_1)

                        Dim conn As New System.Data.SqlClient.SqlConnection(connString)
                        Dim condition As Boolean = True
                        Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
                        Try
                            conn.Open()
                            tran = clsDB.BeginTran(conn)

                            If (clsFc.InsertIportNumber(Iport_Number, conn, tran) > 0) Then
                                For Each dr As SAP_IPORT.BAPIRET1 In BABITable12
                                    If (dr.Type = "E") And (dr.Id = "VF") And (dr.Number = "140") Then
                                        chkcredit = False
                                    End If
                                    If (clsFc.InsertSAP_Table_MESSAGE(Iport_Number, "Zbapi_Iport_Sd_Proc_Cr_Sales", dr.Type, dr.Id, dr.Number, dr.Message, dr.Log_No, dr.Log_Msg_No, dr.Message_V1, dr.Message_V2, dr.Message_V3, dr.Message_V4, conn, tran) < 1) Then
                                        condition = False
                                    End If
                                Next

                                If (condition) Then
                                    Dim Credit_limit As String = ""
                                    If (chkcredit) Then
                                        Credit_limit = "Y"
                                    Else
                                        Credit_limit = "N"
                                    End If
                                    If (clsFc.InsertSaleOrder(Booking_no, Iport_Number, BABIHEADER12.Doc_Type, BABIHEADER12.Req_Date_H, BABIHEADER12.Sold_To, BABIHEADER12.Bill_To, BABIHEADER12.Ship_Name, BABIHEADER12.Division, EX_SALES_NO12, EX_BILL_NO12, Credit_limit, "", "", "", Bill_Date, conn, tran) > 0) Then
                                        For Each dr As SAP_IPORT.ZBAPI_SALES_ITEMS In SALE_TABLE12_1
                                            If (dr.Material <> "") Then
                                                If (clsFc.InsertSAP_Sale_Order_Material(Iport_Number, dr.Material, dr.Plant, dr.Target_Qty, dr.Target_Qu, dr.Cond_Type, dr.Discount, dr.Amount, dr.Condvalue, conn, tran) < 1) Then
                                                    condition = False
                                                End If
                                            End If
                                        Next
                                    Else
                                        condition = False
                                    End If
                                Else
                                    condition = False
                                End If
                            Else
                                condition = False
                            End If

                            If (condition) Then
                                clsDB.CommitTran(tran)
                            Else
                                clsDB.RollBackTran(tran)
                                conditionMaster = False
                            End If

                        Catch ex As Exception
                            clsDB.RollBackTran(tran)
                            conditionMaster = False
                        End Try
                        conn.Dispose()
                    End If
                    If SALE_TABLE12_5.Count > 0 Then
                        Iport_Number = Iport_Number.Substring(0, 8) & "-" & (CInt(Iport_Number.Substring(9, 3)) + 1).ToString("000")
                        SAP_Data.Zbapi_Iport_Sd_Proc_Cr_Sales(Bill_Date, "X", Iport_Number, BABIONETIME12, BABIHEADER12, EX_BILL_NO12, EX_SALES_NO12, BABITable12, SALE_TABLE12_5)

                        Dim conn As New System.Data.SqlClient.SqlConnection(connString)
                        Dim condition As Boolean = True
                        Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
                        Try
                            conn.Open()
                            tran = clsDB.BeginTran(conn)

                            If (clsFc.InsertIportNumber(Iport_Number, conn, tran) > 0) Then
                                For Each dr As SAP_IPORT.BAPIRET1 In BABITable12
                                    If (dr.Type = "E") And (dr.Id = "VF") And (dr.Number = "140") Then
                                        chkcredit = False
                                    End If
                                    If (clsFc.InsertSAP_Table_MESSAGE(Iport_Number, "Zbapi_Iport_Sd_Proc_Cr_Sales", dr.Type, dr.Id, dr.Number, dr.Message, dr.Log_No, dr.Log_Msg_No, dr.Message_V1, dr.Message_V2, dr.Message_V3, dr.Message_V4, conn, tran) < 1) Then
                                        condition = False
                                    End If
                                Next

                                If (condition) Then
                                    Dim Credit_limit As String = ""
                                    If (chkcredit) Then
                                        Credit_limit = "Y"
                                    Else
                                        Credit_limit = "N"
                                    End If
                                    If (clsFc.InsertSaleOrder(Booking_no, Iport_Number, BABIHEADER12.Doc_Type, BABIHEADER12.Req_Date_H, BABIHEADER12.Sold_To, BABIHEADER12.Bill_To, BABIHEADER12.Ship_Name, BABIHEADER12.Division, EX_SALES_NO12, EX_BILL_NO12, Credit_limit, "", "", "", Bill_Date, conn, tran) > 0) Then
                                        For Each dr As SAP_IPORT.ZBAPI_SALES_ITEMS In SALE_TABLE12_5
                                            If (dr.Material <> "") Then
                                                If (clsFc.InsertSAP_Sale_Order_Material(Iport_Number, dr.Material, dr.Plant, dr.Target_Qty, dr.Target_Qu, dr.Cond_Type, dr.Discount, dr.Amount, dr.Condvalue, conn, tran) < 1) Then
                                                    condition = False
                                                End If
                                            End If
                                        Next
                                    Else
                                        condition = False
                                    End If
                                Else
                                    condition = False
                                End If
                            Else
                                condition = False
                            End If

                            If (condition) Then
                                clsDB.CommitTran(tran)
                            Else
                                clsDB.RollBackTran(tran)
                                conditionMaster = False
                            End If

                        Catch ex As Exception
                            clsDB.RollBackTran(tran)
                            conditionMaster = False
                        End Try
                        conn.Dispose()
                    End If
                End If
            Next
            If (conditionMaster) Then
                Dim conn As New System.Data.SqlClient.SqlConnection(connString)
                Dim condition As Boolean = True
                Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
                Try
                    conn.Open()
                    tran = clsDB.BeginTran(conn)
                    Dim Credit_limit As String = ""
                    If (chkcredit) Then
                        Credit_limit = "Y"
                    Else
                        Credit_limit = "N"
                    End If
                    Dim ds_Log As DataTable = clsGet.Get_Booking_LOG(ViewState("EditBooking"))
                    Dim Booking_Log As String = Date.Now.AddSeconds(10.1).ToString("yyyyMMddHHmmss")
                    If (clsFc.UpdateCreditLimit(Booking_no, Credit_limit, conn, tran) > 0) Then
                        If (clsFc.InsertBooking_Log(Booking_Log, ViewState("EditBooking"), ds_Log.Rows(0).Item("Booking_Code"), ds_Log.Rows(0).Item("Booking_name"), ds_Log.Rows(0).Item("Vehicle_no"), ds_Log.Rows(0).Item("Vehicle_Text"), ds_Log.Rows(0).Item("Vehicle_LOA"), ds_Log.Rows(0).Item("Vehicle_DWT"), ds_Log.Rows(0).Item("Vehicle_Draft"), ds_Log.Rows(0).Item("Vehicle_GRT"), ds_Log.Rows(0).Item("Date_From"), ds_Log.Rows(0).Item("Date_To"), ds_Log.Rows(0).Item("PORT"), ds_Log.Rows(0).Item("Vehicle_destination"), ds_Log.Rows(0).Item("Vehicle_TypeBuy"), ds_Log.Rows(0).Item("Remark"), Status, ds_Log.Rows(0).Item("Remark_VPS"), ds_Log.Rows(0).Item("VPS_approve"), ds_Log.Rows(0).Item("Remark_MRI"), ds_Log.Rows(0).Item("MRI_approve"), VPS, ds_Log.Rows(0).Item("Product_name"), ds_Log.Rows(0).Item("Product_Amount"), ds_Log.Rows(0).Item("MAgent_no"), ds_Log.Rows(0).Item("MAgent_name"), ds_Log.Rows(0).Item("SAgent_no"), ds_Log.Rows(0).Item("SAgent_name"), ds_Log.Rows(0).Item("Booking_Date"), ds_Log.Rows(0).Item("Booking_Time"), ds_Log.Rows(0).Item("Buyer"), ds_Log.Rows(0).Item("Seller"), ds_Log.Rows(0).Item("Product_Unit"), ds_Log.Rows(0).Item("File_Upload"), ds_Log.Rows(0).Item("Vehicle_CNTRY"), ds_Log.Rows(0).Item("Lay_Time"), ds_Log.Rows(0).Item("MKT_Product"), ds_Log.Rows(0).Item("MKT_Custom"), ds_Log.Rows(0).Item("MKT_Finance"), ds_Log.Rows(0).Item("BunkerFO_chk"), ds_Log.Rows(0).Item("BunkerDO_chk"), ds_Log.Rows(0).Item("BunkerFO_Point"), ds_Log.Rows(0).Item("BunkerDO_Point"), ds_Log.Rows(0).Item("BunkerDetail"), ds_Log.Rows(0).Item("Water_Point"), ds_Log.Rows(0).Item("MKT_Approve"), ds_Log.Rows(0).Item("Cancel_By"), ds_Log.Rows(0).Item("Cancel_Description"), ds_Log.Rows(0).Item("Vps_Acknowledge"), ds_Log.Rows(0).Item("MKT_Acknowledge"), radioPayin.SelectedValue, Bill_to_no, Bill_to_name, ds_Log.Rows(0).Item("StandardTime"), Credit_limit, ds_Log.Rows(0).Item("Status_Pay"), ds_Log.Rows(0).Item("Demurrage"), ds_Log.Rows(0).Item("Demurrage_Money"), ds_Log.Rows(0).Item("Electricity") & "", ds_Log.Rows(0).Item("Shifting") & "", conn, tran) < 1) Then
                            condition = False
                        End If
                    Else
                        condition = False
                    End If
                    If (condition) Then
                        clsDB.CommitTran(tran)
                    Else
                        clsDB.RollBackTran(tran)
                        conditionMaster = False
                    End If
                Catch ex As Exception
                    clsDB.RollBackTran(tran)
                    conditionMaster = False
                End Try
                conn.Dispose()
            End If
            ClassSAP.SAP_CLOSE(SAP_Data)
            Return chkcredit

        Catch ex As Exception

        End Try
    End Function

    Private Sub gridfile_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gridfile.RowCommand
        Dim Index As Integer = Convert.ToInt32(e.CommandArgument)
        If (e.CommandName = "Select") Then

            Dim FileName As String = gridfile.DataKeys(Index).Values("File_name")
            Dim FileGen As String = gridfile.DataKeys(Index).Values("File_nameGuid") & gridfile.DataKeys(Index).Values("File_Type")
            ' Dim FileType As String = gridfile.DataKeys(Index).Values("File_Type")
            Dim ContentType As String = gridfile.DataKeys(Index).Values("File_ContentType").ToString().Replace(".", "")

            Dim script As String = "window.open('IPORTDownloadfile.aspx?str2=" + FileGen + "&str3=." + ContentType + "&str4=" + FileName + "','_blank','left=0,top=0,location=no,menubar= no,resizable=yes,scrollbars=no,toolbar=no,status=no,width=100px,height=50px');"
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", script, True)
        End If
    End Sub

    Private Sub GetCreditLimit(ByVal Customer_no As String)
        Dim ClassSAP As New Class_SAP
        Dim SAP_Data As Object = ClassSAP.SAP_OPEN()
        Dim IM_CR_AREA As String = "1004"
        Dim EX_SUBRC As Integer

        Dim Input_Value As New SAP_IPORT.ZBAPI_LIMITED_INPUT
        Input_Value.Customer = Customer_no
        Dim Input_Table As New SAP_IPORT.ZBAPI_LIMITED_INPUTTable
        Input_Table.Insert(0, Input_Value)
        Dim CR_Limit As New SAP_IPORT.ZBAPI_CREDIT_LIMITEDTable
        Try
            SAP_Data.Zbapi_Iport_Cr_Limited_Master(IM_CR_AREA, EX_SUBRC, CR_Limit, Input_Table)
            For Each dr As SAP_IPORT.ZBAPI_CREDIT_LIMITED In CR_Limit
                lbLimit.Text = dr.Cred_Limit
                lbUse.Text = dr.Cred_Used
                lbSalesValue.Text = dr.Sales_Val
                lbTotal.Text = dr.Recbl_Vals
                lbAvailable.Text = dr.Cred_Availb
            Next
        Catch ex As Exception
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('พบปัญหาเกี่ยวกับการเชื่อมต่อกับ SAP !!');", True)
        End Try
        ClassSAP.SAP_CLOSE(SAP_Data)
    End Sub

    Private Sub btnCancelBookingView_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancelBookingView.Click
        If (Session("Role") & "" = "00003") Then
            Session("StatusCancel") = "VPSMRI"
        ElseIf (Session("Role") & "" = "00004") Then
            Session("StatusCancel") = "MARKETING"
        End If
        ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " document.getElementById('ctl00_contentplaceholder1_CancelPopup').src = '../FormPopup/Cancel_popup.aspx?Type=Manage';", True)
        ModalPopupExtender6.Show()
    End Sub

    Private Sub btnSaveVPS_SaleMarketing_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSaveVPS_SaleMarketing.Click
        SaveEventProduct_Custom_Finance("VPS")
    End Sub

    Private Sub InsertSchedule(ByVal Event_Type As String)
        'If (ddlWharf.SelectedValue = "0") Then
        '    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการเลือก Wharf');", True)
        '    Exit Sub
        'End If
        'If (CDate(txtDateShip.Text) > CDate(txtDateToShip.Text)) Then
        '    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ข้อมูลเวลาการจองท่าเรือไม่ถูกต้อง');", True)
        '    Exit Sub
        'End If
        'Dim conn As New System.Data.SqlClient.SqlConnection(connString)
        'Dim clsDB As New ClassDatabase
        'Dim clsFc As New ClassFunction
        'Dim condition As Boolean = True
        'Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
        'Dim User_Create As String = CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("User_name") & " " & DateTime.Now.ToString("yyyyMMdd:HHmmss")
        'Application.Lock()
        'conn.Open()
        'tran = clsDB.BeginTran(conn)
        'clsFc.DeleteBookingWharf(ViewState("EditBooking"), conn, tran)
        'If (clsFc.InsertBooking_Wharf(ViewState("EditBooking"), ddlWharf.SelectedValue, txtDateShip.Text, txtDateToShip.Text, txtTimeBookingStart.Text, txtTimeBookingEnd.Text, txtRemarkSchedule.Text, User_Create, CDate(txtDateShip.Text).ToString("dd/MM/yyyy"), CDate(txtDateToShip.Text).ToString("dd/MM/yyyy"), Event_Type, txtBooking.Text, txtNoteSchedule.Text, conn, tran) < 1) Then
        '    condition = False
        'End If
        'If (txtBooking.Text <> "") Then
        '    If (clsFc.UpdateFor_Shifting(txtBooking.Text, ViewState("EditBooking"), conn, tran) < 1) Then
        '        condition = False
        '    End If
        'End If
        'If (condition) Then
        '    clsDB.CommitTran(tran)
        '    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('บันทึกข้อมูลเรียบร้อย');", True)
        'Else
        '    clsDB.RollBackTran(tran)
        '    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการบันทึก');", True)
        'End If
        'Application.UnLock()
        'conn.Dispose()
    End Sub

    'Private Sub btnSaveSchedule_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSaveSchedule.Click
    '    InsertSchedule("N")
    'End Sub

    'Private Sub btnConfirm_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnConfirm.Click
    '    InsertSchedule("Y")
    'End Sub

    Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        If (Session("Role") & "" <> "00003") Then
            LoadBOoking()
        End If
        For i As Integer = 0 To gridItem.Rows.Count - 1
            Dim dsBooking As DataSet = clsGet.Get_BookingOneRecord(gridItem.DataKeys(i).Values("Booking_no"))
            If (dsBooking.Tables(0).Rows(0).Item("Lay_Time") & "" <> "0") Then
                Dim dtLogIn As DataTable = clsGet.Get_Booking_LogSheet_In(gridItem.DataKeys(i).Values("Booking_no"))
                If Not (dtLogIn.Rows.Count = 0) Then
                    If Not (dtLogIn.Rows(0).Item("Berthing_Date") & "" = "") Or (dtLogIn.Rows(0).Item("Berthing_TimeTo") & "" = "") Then
                        If Not (dtLogIn.Rows(0).Item("POB_Date") & "" = "") Or (dtLogIn.Rows(0).Item("POB_Time") & "" = "") Then
                            Dim dtProduct As DataTable = clsGet.Get_Booking_Product(gridItem.DataKeys(i).Values("Booking_no"))
                            If Not (dtProduct.Rows.Count = 0) Then
                                If (dsBooking.Tables(0).Rows(0).Item("PORT") & "" = "L") Then
                                    Dim Product_no As String = ""
                                    Try
                                        Dim sort As Integer = 0
                                        For Each dr As DataRow In dtProduct.Rows
                                            If (CInt(dr.Item("Product_Index") & "") > sort) Then
                                                sort = CInt(dr.Item("Product_Index"))
                                                Product_no = dr.Item("Product_no")
                                            End If
                                        Next
                                    Catch ex As Exception

                                    End Try
                                    Dim dtLoad As DataTable = clsGet.Get_Load_Unload_Vessel(gridItem.DataKeys(i).Values("Booking_no"))
                                    Dim NOR As String = ""
                                    Dim NOR_Time As String = ""
                                    Dim POB As String = ""
                                    Dim POB_Time As String = ""
                                    If (dtLoad.Rows.Count > 0) Then
                                        If (dtLoad.Rows(0).Item("NOR_Date") & "" <> "") Then
                                            NOR = dtLoad.Rows(0).Item("NOR_Date").ToString.Substring(0, 2) & " " & GetNameMonth(dtLoad.Rows(0).Item("NOR_Date").ToString.Substring(3, 2)) & " 20" & dtLoad.Rows(0).Item("NOR_Date").ToString.Substring(6, 2)
                                            NOR_Time = dtLoad.Rows(0).Item("NOR_Time") & ""
                                        Else
                                            NOR = dtLogIn.Rows(0).Item("NOR_Date") & ""
                                            NOR_Time = dtLogIn.Rows(0).Item("NOR_Time") & ""
                                        End If
                                    Else
                                        NOR = dtLogIn.Rows(0).Item("NOR_Date") & ""
                                        NOR_Time = dtLogIn.Rows(0).Item("NOR_Time") & ""
                                    End If
                                    If (dtLogIn.Rows(0).Item("POB_Date") & "" <> "") Then
                                        If (dtLogIn.Rows(0).Item("Up_Date") & "" <> "") Then
                                            If (CDate(dtLogIn.Rows(0).Item("POB_Date")) < CDate(dtLogIn.Rows(0).Item("Up_Date"))) Then
                                                POB = dtLogIn.Rows(0).Item("Up_Date") & ""
                                                POB_Time = dtLogIn.Rows(0).Item("Up_Time") & ""
                                            ElseIf (CDate(dtLogIn.Rows(0).Item("POB_Date")) = CDate(dtLogIn.Rows(0).Item("Up_Date"))) Then
                                                If (CInt(dtLogIn.Rows(0).Item("POB_Time").ToString().Split(":")(0)) < CInt(dtLogIn.Rows(0).Item("Up_Time").ToString().Split(":")(0))) Then
                                                    POB = dtLogIn.Rows(0).Item("Up_Date") & ""
                                                    POB_Time = dtLogIn.Rows(0).Item("Up_Time") & ""
                                                ElseIf (CInt(dtLogIn.Rows(0).Item("POB_Time").ToString().Split(":")(0)) = CInt(dtLogIn.Rows(0).Item("Up_Time").ToString().Split(":")(0))) Then
                                                    If (CInt(dtLogIn.Rows(0).Item("POB_Time").ToString().Split(":")(1)) < CInt(dtLogIn.Rows(0).Item("Up_Time").ToString().Split(":")(1))) Then
                                                        POB = dtLogIn.Rows(0).Item("Up_Date") & ""
                                                        POB_Time = dtLogIn.Rows(0).Item("Up_Time") & ""
                                                    Else
                                                        POB = dtLogIn.Rows(0).Item("POB_Date") & ""
                                                        POB_Time = dtLogIn.Rows(0).Item("POB_Time") & ""
                                                    End If
                                                Else
                                                    POB = dtLogIn.Rows(0).Item("POB_Date") & ""
                                                    POB_Time = dtLogIn.Rows(0).Item("POB_Time") & ""
                                                End If
                                            Else
                                                POB = dtLogIn.Rows(0).Item("POB_Date") & ""
                                                POB_Time = dtLogIn.Rows(0).Item("POB_Time") & ""
                                            End If
                                        Else
                                            POB = dtLogIn.Rows(0).Item("POB_Date") & ""
                                            POB_Time = dtLogIn.Rows(0).Item("POB_Time") & ""
                                        End If
                                    Else
                                        POB = dtLogIn.Rows(0).Item("Up_Date") & ""
                                        POB_Time = dtLogIn.Rows(0).Item("Up_Time") & ""
                                    End If

                                    dtLoad = clsGet.Get_Load_Unload_Product(gridItem.DataKeys(i).Values("Booking_no"), Product_no)
                                    Dim Dis_Date As String = ""
                                    Dim Dis_Time As String = ""
                                    For Each dl As DataRow In dtLoad.Rows
                                        Try
                                            If (Dis_Date = "") Then
                                                Dis_Date = dl.Item("LU_Disconnect_Date") & ""
                                                Dis_Time = dl.Item("LU_Disconnect_To") & ""
                                            End If
                                            Dim _DD As String = Dis_Date.Substring(0, 2) & " " & GetNameMonth(Dis_Date.Substring(3, 2)) & " " & CInt("20" & Dis_Date.Substring(6, 2))
                                            Dim _D2 As String = dl.Item("LU_Disconnect_Date").Substring(0, 2) & " " & GetNameMonth(dl.Item("LU_Disconnect_Date").Substring(3, 2)) & " " & CInt("20" & dl.Item("LU_Disconnect_Date").Substring(6, 2))
                                            If (CDate(_DD) < CDate(_D2)) Then
                                                Dis_Date = dl.Item("LU_Disconnect_Date") & ""
                                                Dis_Time = dl.Item("LU_Disconnect_To") & ""
                                            ElseIf (CDate(_DD) = CDate(_D2)) Then
                                                If (CInt(Dis_Time.Split(":")(0)) < CInt(dl.Item("LU_Disconnect_To").ToString.Split(":")(0))) Then
                                                    Dis_Date = dl.Item("LU_Disconnect_Date") & ""
                                                    Dis_Time = dl.Item("LU_Disconnect_To") & ""
                                                ElseIf (CInt(Dis_Time.Split(":")(0)) = CInt(dl.Item("LU_Disconnect_To").ToString.Split(":")(0))) Then
                                                    Try
                                                        If (CInt(Dis_Time.Split(":")(1)) < CInt(dl.Item("LU_Disconnect_To").ToString.Split(":")(1))) Then
                                                            Dis_Date = dl.Item("LU_Disconnect_Date") & ""
                                                            Dis_Time = dl.Item("LU_Disconnect_To") & ""
                                                        End If
                                                    Catch ex As Exception

                                                    End Try
                                                End If
                                            End If
                                        Catch ex As Exception

                                        End Try

                                    Next
                                    Dim Berthing_Date As String = dtLogIn.Rows(0).Item("Berthing_Date")
                                    Try
                                        Try
                                            If (CInt(dtLogIn.Rows(0).Item("Berthing_TimeTo").ToString().Split(":")(0)) < CInt(dtLogIn.Rows(0).Item("Berthing_TimeFrom").ToString.Split(":")(0))) Then
                                                Berthing_Date = CDate(Berthing_Date).AddDays(1).ToString("dd MMM", New CultureInfo("en-US")) & " " & Berthing_Date.Split(" ")(2)
                                            End If
                                        Catch ex As Exception

                                        End Try
                                    Catch ex As Exception

                                    End Try

                                    If (dtLoad.Rows.Count > 0) Then
                                        gridItem.Rows(i).Cells(28).Text = clsGet.ComputeRemainLaytime(Berthing_Date, dtLogIn.Rows(0).Item("Berthing_TimeTo"), dsBooking.Tables(0).Rows(0).Item("Lay_Time"), dsBooking.Tables(0).Rows(0).Item("Date_From"), dsBooking.Tables(0).Rows(0).Item("Date_To"), POB, POB_Time, Dis_Date & "", Dis_Time & "", NOR, NOR_Time)
                                    Else
                                        gridItem.Rows(i).Cells(28).Text = clsGet.ComputeRemainLaytime(Berthing_Date, dtLogIn.Rows(0).Item("Berthing_TimeTo"), dsBooking.Tables(0).Rows(0).Item("Lay_Time"), dsBooking.Tables(0).Rows(0).Item("Date_From"), dsBooking.Tables(0).Rows(0).Item("Date_To"), POB, POB_Time, "", "", NOR, NOR_Time)
                                    End If

                                Else
                                    'Bulk
                                    Dim dtProductBulk As DataTable = clsGet.Get_Booking_Product(gridItem.DataKeys(i).Values("Booking_no"))
                                    If (dtProductBulk.Rows.Count > 0) Then
                                        Dim chkCoil As Boolean = False
                                        For Each dx As DataRow In dtProductBulk.Rows
                                            If (dx.Item("Group_no") & "" = "00007") Then
                                                chkCoil = True
                                                Exit For
                                            End If
                                        Next
                                        If (chkCoil) Then
                                            gridItem.Rows(i).Cells(28).Text = clsGet.ComputeRemainLaytimeBulk(dsBooking.Tables(0).Rows(0).Item("Lay_Time"), gridItem.DataKeys(i).Values("Booking_no"))
                                        End If
                                    End If

                                End If
                                If (gridItem.Rows(i).Cells(28).Text <> "") Then
                                    If (gridItem.Rows(i).Cells(28).Text.Substring(0, 1) = "-") Then
                                        gridItem.Rows(i).Cells(28).ForeColor = Drawing.Color.Red
                                    Else
                                        gridItem.Rows(i).Cells(28).ForeColor = Drawing.Color.Black
                                    End If
                                End If

                            End If
                        End If
                    End If
                End If
            End If


        Next
    End Sub

    Private Function GetNameMonth(ByVal Month As String) As String
        Try
            Select Case (CInt(Month).ToString("00"))
                Case "01"
                    Return "Jan"
                Case "02"
                    Return "Feb"
                Case "03"
                    Return "Mar"
                Case "04"
                    Return "Apr"
                Case "05"
                    Return "May"
                Case "06"
                    Return "Jun"
                Case "07"
                    Return "Jul"
                Case "08"
                    Return "Aug"
                Case "09"
                    Return "Sep"
                Case "10"
                    Return "Oct"
                Case "11"
                    Return "Nov"
                Case "12"
                    Return "Dec"
                Case Else
                    Return ""
            End Select
        Catch ex As Exception
            Return Month
        End Try

    End Function

    Private Sub btnComputeOld_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnComputeOld.Click
        Session("ViewestimeteOld") = ViewState("EditBooking")
        Session("Booking_no_ESTIMATE") = ViewState("EditBooking")
        Session("Owner_OLD_ESTIMATE") = ViewState("Owner")
        Session("Status_Pay") = "Y"
        ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " document.getElementById('ctl00_contentplaceholder1_framePopup2').src = '../FormPopup/estimate.aspx';", True)
        ModalPopupExtender2.Show()
    End Sub

    Private Sub gridItemMarketing_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gridItemMarketing.RowCommand
        Dim Index As Integer = Convert.ToInt32(e.CommandArgument)
        If (gridItemMarketing.PageIndex <> 0) Then
            Index = Index Mod (gridItemMarketing.PageIndex * 10)
        End If
        If e.CommandName = "Edit" Then
            Dim Customer_no As String = ""
            Dim Customer_name As String = ""
            If (gridItemMarketing.DataKeys(Index).Values("PORT") & "" = "B") Then
                Customer_no = gridItemMarketing.DataKeys(Index).Values("Owner_Product_no") & ""
                Customer_name = gridItemMarketing.DataKeys(Index).Values("Owner_Product_name") & ""
            End If
            Dim dt As DataTable = clsGet.Get_Add_Tariff_New(gridItemMarketing.DataKeys(Index).Values("Booking_no") & "", "N")
            If (dt.Rows.Count > 0) Then
                Dim ServiceText As String = "ลูกค้า " & Customer_name & "<br />รายการจองที่ Booking No. " & dt.Rows(0).Item("Booking_no") & " ได้ทำการของเพิ่มบริการดังนี้ <br />"
                Dim count As Integer = 0
                For Each dr As DataRow In dt.Rows
                    count += 1
                    If (dr.Item("Material") = "WP") Then
                        ServiceText &= "&nbsp;<br /> " & count & ". ขอใช้บริการน้ำเป็นจำนวนโดยประมาณ " & dr.Item("Count") & " Ton"
                    ElseIf (dr.Item("Material") = "000000002100000236") Then
                        ServiceText &= "&nbsp;<br /> " & count & ". ขอใช้บริการเรือทักเป็นจำนวนโดยประมาณ " & dr.Item("Count") & " ลำ"
                    End If
                Next
                If (dt.Rows(0).Item("Description_ByCustomer") & "" <> "") Then
                    ServiceText &= "&nbsp;<br /> - " & dt.Rows(0).Item("Description_ByCustomer")
                End If

                LabelService.Text = ServiceText & "<br />"
                hdfBooking.Value = gridItemMarketing.DataKeys(Index).Values("Booking_no") & "$" & Customer_no & "$" & Customer_name & "$" & gridItemMarketing.DataKeys(Index).Values("PORT") & "$" & gridItemMarketing.DataKeys(Index).Values("Marketing_approve")
                ModalPopupExtender7.Show()
            Else
                ViewState("Owner") = Customer_no
                EditBooking(gridItemMarketing.DataKeys(Index).Values("Booking_no"), Customer_no, Customer_name, gridItemMarketing.DataKeys(Index).Values("Marketing_approve") & "")
            End If

        End If
    End Sub

    Private Sub gridItemMarketing_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gridItemMarketing.RowDataBound
        If (e.Row.RowType = DataControlRowType.DataRow) Then
            'If (ViewState("Booking_OLD") & "" = gridItemMarketing.DataKeys(e.Row.RowIndex).Values("Booking_no")) Then
            '    e.Row.Cells(0).Text = ""
            'End If
            'ViewState("Booking_OLD") = gridItemMarketing.DataKeys(e.Row.RowIndex).Values("Booking_no")
            Try
                e.Row.Cells(3).Text = gridItemMarketing.DataKeys(e.Row.RowIndex).Values("Date_From") & "-" & gridItemMarketing.DataKeys(e.Row.RowIndex).Values("Date_To") & "<<"
            Catch ex As Exception

            End Try
            Dim dtWharf As DataTable = clsGet.Get_BookingWharf(gridItemMarketing.DataKeys(e.Row.RowIndex).Values("Booking_no"))
            If (dtWharf.Rows.Count > 0) Then
                Try
                    e.Row.Cells(4).Text = dtWharf.Rows(0).Item("Date_From") & " - " & dtWharf.Rows(0).Item("TimeStart")
                Catch ex As Exception

                End Try
            End If

            If (gridItemMarketing.DataKeys(e.Row.RowIndex).Values("PORT") & "" = "L") Then
                If (gridItemMarketing.DataKeys(e.Row.RowIndex).Values("Vehicle_Destination") & "" = "I") Then
                    e.Row.Cells(2).Text = "Liquid(D)"
                Else
                    e.Row.Cells(2).Text = "Liquid(F)"
                End If
            Else
                If (gridItemMarketing.DataKeys(e.Row.RowIndex).Values("Vehicle_Destination") & "" = "I") Then
                    e.Row.Cells(2).Text = "Bulk(D)"
                Else
                    e.Row.Cells(2).Text = "Bulk(F)"
                End If
            End If
            Dim imgStatus As Image = CType(e.Row.FindControl("imgStatus"), Image)
            Dim imgCredit As Image = CType(e.Row.FindControl("imgCredit"), Image)
            Dim imgService As Image = CType(e.Row.FindControl("imgService"), Image)

            Dim dt As DataTable = clsGet.Get_Add_Tariff_New(gridItemMarketing.DataKeys(e.Row.RowIndex).Values("Booking_no") & "", "N")
            If (dt.Rows.Count > 0) Then
                imgService.Visible = True
            Else
                imgService.Visible = False
            End If
            If (gridItemMarketing.DataKeys(e.Row.RowIndex).Values("MAgent_no") & "" = gridItemMarketing.DataKeys(e.Row.RowIndex).Values("Owner_Product_no") & "") Then
                If (gridItemMarketing.DataKeys(e.Row.RowIndex).Values("Marketing_approve") & "" <> "") Then
                    imgStatus.ImageUrl = "~/Image/green.png"
                Else
                    imgStatus.ImageUrl = "~/Image/red.png"
                End If
                If (gridItemMarketing.DataKeys(e.Row.RowIndex).Values("Credit_Limit") & "" = "Y") Then
                    imgCredit.ImageUrl = "~/Image/green.png"
                ElseIf (gridItemMarketing.DataKeys(e.Row.RowIndex).Values("Credit_Limit") & "" = "N") Then
                    imgCredit.ImageUrl = "~/Image/red.png"
                Else
                    imgCredit.ImageUrl = "~/Image/green.png"
                End If
                If (gridItemMarketing.DataKeys(e.Row.RowIndex).Values("Payin") & "" = "0") Then
                    e.Row.Cells(12).Text = "C"
                    Dim customer As String = ""
                    If (gridItemMarketing.DataKeys(e.Row.RowIndex).Values("MAgent_no") & "" = gridItemMarketing.DataKeys(e.Row.RowIndex).Values("Owner_Product_no") & "") Then
                        customer = gridItemMarketing.DataKeys(e.Row.RowIndex).Values("MAgent_no") & ""
                    Else
                        customer = gridItemMarketing.DataKeys(e.Row.RowIndex).Values("Owner_Product_no") & ""
                    End If
                    dt = clsGet.Get_Booking_Gl_Account(gridItemMarketing.DataKeys(e.Row.RowIndex).Values("Booking_no"), customer)
                    If (dt.Rows.Count > 0) Then
                        e.Row.Cells(13).Text = dt.Rows(0).Item("Value_Date") & ""
                        e.Row.Cells(14).Text = dt.Rows(0).Item("Gl_Name") & ""
                        Try
                            'e.Row.Cells(15).Text = FormatNumber(dt.Rows(0).Item("Amount"), 2)
                        Catch ex As Exception
                            'e.Row.Cells(15).Text = dt.Rows(0).Item("Amount") & ""
                        End Try
                        Try
                            Dim dtBill As DataTable = clsGet.Get_Billing_Advanct(dt.Rows(0).Item("Iport_no") & "")
                            If (dtBill.Rows.Count > 0) Then
                                e.Row.Cells(16).Text = dtBill.Rows(0).Item("EX_BILL_NO") & ""
                            End If

                        Catch ex As Exception

                        End Try
                    End If
                Else
                    e.Row.Cells(12).Text = "CR"
                End If
            Else
                If (gridItemMarketing.DataKeys(e.Row.RowIndex).Values("Type_Pay_Product") & "" <> "") Then
                    imgStatus.ImageUrl = "~/Image/green.png"
                Else
                    imgStatus.ImageUrl = "~/Image/red.png"
                End If
                Dim dtProduct_owner As DataTable = clsGet.Get_Booking_Product(gridItemMarketing.DataKeys(e.Row.RowIndex).Values("Booking_no"), gridItemMarketing.DataKeys(e.Row.RowIndex).Values("Owner_Product_no") & "")
                If (dtProduct_owner.Rows.Count > 0) Then
                    If (dtProduct_owner.Rows(0).Item("Credit_Limit") & "" = "Y") Then
                        imgCredit.ImageUrl = "~/Image/green.png"
                    ElseIf (dtProduct_owner.Rows(0).Item("Credit_Limit") & "" = "N") Then
                        imgCredit.ImageUrl = "~/Image/red.png"
                    Else
                        imgCredit.ImageUrl = "~/Image/green.png"
                    End If
                    If (dtProduct_owner.Rows(0).Item("Type_Pay") & "" = "0") Then
                        e.Row.Cells(12).Text = "C"
                        Dim customer As String = ""
                        If (gridItemMarketing.DataKeys(e.Row.RowIndex).Values("MAgent_no") & "" = gridItemMarketing.DataKeys(e.Row.RowIndex).Values("Owner_Product_no") & "") Then
                            customer = gridItemMarketing.DataKeys(e.Row.RowIndex).Values("MAgent_no") & ""
                        Else
                            customer = gridItemMarketing.DataKeys(e.Row.RowIndex).Values("Owner_Product_no") & ""
                        End If
                        dt = clsGet.Get_Booking_Gl_Account(gridItemMarketing.DataKeys(e.Row.RowIndex).Values("Booking_no"), customer)
                        If (dt.Rows.Count > 0) Then
                            e.Row.Cells(13).Text = dt.Rows(0).Item("Value_Date") & ""
                            e.Row.Cells(14).Text = dt.Rows(0).Item("Gl_Name") & ""
                            Try
                                'e.Row.Cells(15).Text = FormatNumber(dt.Rows(0).Item("Amount"), 2)
                            Catch ex As Exception
                                'e.Row.Cells(15).Text = dt.Rows(0).Item("Amount") & ""
                            End Try
                            Try
                                Dim dtBill As DataTable = clsGet.Get_Billing_Advanct(dt.Rows(0).Item("Iport_no") & "")
                                If (dtBill.Rows.Count > 0) Then
                                    e.Row.Cells(16).Text = dtBill.Rows(0).Item("EX_BILL_NO") & ""
                                End If

                            Catch ex As Exception

                            End Try
                        End If
                    Else
                        e.Row.Cells(12).Text = "CR"
                    End If
                End If


            End If



            Dim dtP As DataTable = clsGet.Get_Booking_Product(gridItemMarketing.DataKeys(e.Row.RowIndex).Values("Booking_no"))
            If dtP.Rows.Count > 0 Then
                Dim Product As String = ""
                Dim Amount As String = "0.00"
                For Each dr As DataRow In dtP.Rows
                    If (dr.Item("Product_no") & "" <> "") Then
                        If Product <> "" Then
                            Product &= ",(" & dr.Item("Product_Event") & ")" & dr.Item("Product_name")
                        Else
                            Product &= "(" & dr.Item("Product_Event") & ")" & dr.Item("Product_name")
                        End If
                        Amount = (CDbl(Amount) + CDbl(dr.Item("Product_Amount"))).ToString("##############0.00")
                    End If
                Next
                e.Row.Cells(6).Text = Product
                e.Row.Cells(7).Text = Amount
            End If

        ElseIf (e.Row.RowType = DataControlRowType.Pager) Then
            Dim Page As GridViewRow = gridItemMarketing.BottomPagerRow
            Dim ddlPage As DropDownList = CType(e.Row.FindControl("ddlPage"), DropDownList)
            Dim lblPageCount As Label = CType(e.Row.FindControl("lbPageCount"), Label)
            If Not (ddlPage Is Nothing) Then
                For i As Integer = 0 To gridItemMarketing.PageCount - 1
                    Dim intPageNumber As Integer = i + 1
                    Dim IsItem As New ListItem(intPageNumber.ToString())
                    If (i = gridItemMarketing.PageIndex) Then
                        IsItem.Selected = True
                    End If
                    ddlPage.Items.Add(IsItem)
                Next
            End If
            If Not (lblPageCount Is Nothing) Then
                lblPageCount.Text = gridItemMarketing.PageCount.ToString()
            End If
        End If
    End Sub

    Private Sub gridItemMarketing_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles gridItemMarketing.RowEditing

    End Sub

    'Private Sub gridItem_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles gridItem.Sorting
    '    Dim sortdata As String = ""
    '    If (ViewState("Sorting").ToString() = "D") Or (ViewState("Sorting").ToString() = "") Then
    '        sortdata = "DESC"
    '        ViewState("Sorting") = "A"
    '    Else
    '        sortdata = ""
    '        ViewState("Sorting") = "D"
    '    End If
    '    Dim ds As DataSet = ViewState("Manage")
    '    Dim dsView As DataView = ds.Tables(0).DefaultView
    '    If e.SortExpression = "LAYCAN" Then
    '        dsView.Sort = " Lay " & sortdata
    '    End If
    '    ds = New DataSet
    '    ds.Tables.Add(clsGet.ConvertDataViewToDataSet(dsView).Copy)
    '    ViewState("Manage") = ds
    '    gridItem.DataSource = ViewState("Manage")
    '    gridItem.DataBind()
    'End Sub

    Private Sub btnTariff_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnTariff.Click
        ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " document.getElementById('ctl00_contentplaceholder1_framePopup').src = '../FormPopup/FrmTariff_Popup.aspx';", True)
        ModalPopupExtender1.Show()
    End Sub

    Private Sub btnReLoad_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnReLoad.Click
        gridItem.DataSource = ViewState("Manage")
        gridItem.DataBind()
        LoadBOoking()
        Timer1_Tick(sender, e)
    End Sub

    Private Sub btnSearchData_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearchData.Click
        Dim ds As DataSet
        If (Session("Role") & "" = "00003") Then
            'Dim DateFrom As String = ""
            'Dim DateTo As String = ""
            'If (txtDateFromM.Text.Trim <> "") And (txtDateToM.Text.Trim() <> "") Then
            '    DateFrom = txtDateFromM.Text.Split(" ")(2) & CDate(txtDateFromM.Text).ToString("MMdd")
            '    DateTo = txtDateToM.Text.Split(" ")(2) & CDate(txtDateToM.Text).ToString("MMdd")
            'End If
            If (ddlStatusMarketing.SelectedValue = "A") Then
                ds = clsGet.Get_BookingMarketing(txtBooking_no.Text, "", False, txtShipName.Text, ddlPORT.SelectedValue, txtMainAgentSearch.Text, "0", "'CV','CC','CM','CR','CA'", "", "")
            Else
                ds = clsGet.Get_BookingMarketing(txtBooking_no.Text, "'CV','CC','CM','CR','CA'", False, txtShipName.Text, ddlPORT.SelectedValue, txtMainAgentSearch.Text, "0", "", "", "")
            End If
            If (txtDateFromM.Text <> "") Then
                Dim c As Integer = 0
                Dim dtTemp As DataTable = ds.Tables(0).Copy
                For i As Integer = 0 To ds.Tables(0).Rows.Count - 1
                    Dim dtLogin As DataTable = clsGet.Get_BookingWharf(ds.Tables(0).Rows(i).Item("Booking_no"))
                    Try
                        If (dtLogin.Rows(0).Item("Date_From") <> txtDateFromM.Text) Then
                            dtTemp.Rows(i - c).Delete()
                            dtTemp.AcceptChanges()
                            c += 1
                        End If
                    Catch ex As Exception
                        dtTemp.Rows(i - c).Delete()
                        dtTemp.AcceptChanges()
                        c += 1
                    End Try
                Next
                ds.Tables.Clear()
                ds.Tables.Add(dtTemp.Copy)
                ds.AcceptChanges()
            End If
            PanelBookingItemAll.Visible = False
            PanelBookingItemMarketing.Visible = True
            If (ds.Tables(0).Rows.Count > 0) Then
                ViewState("Manage") = ds
                gridItemMarketing.DataSource = ViewState("Manage")
                gridItemMarketing.DataBind()
            Else
                gridItemMarketing.DataSource = Nothing
                gridItemMarketing.DataBind()
                lbAlertMarketing.Text = "ไม่พบรายการ Booking"
            End If
        Else
            ds = clsGet.Get_Booking("", "", "", "", True, ddlPORTVPS.SelectedValue.Replace("0", ""), txtShipVPS.Text, "", "", txtBookingVPS.Text, "A", "", "", txtProductSearch.Text)
            PanelBookingItemAll.Visible = True
            PanelBookingItemMarketing.Visible = False
            If (ds.Tables(0).Rows.Count > 0) Then
                ds.Tables(0).Columns.Add("Lay", GetType(String))
                ds.AcceptChanges()
                For i As Integer = 0 To ds.Tables(0).Rows.Count - 1
                    ds.Tables(0).Rows(i).Item("Lay") = CDate(ds.Tables(0).Rows(i).Item("Date_From")).ToString("yyyyMMdd")
                    ds.Tables(0).AcceptChanges()
                Next
                Dim dsView As DataView = ds.Tables(0).DefaultView
                dsView.Sort = " Lay DESC"
                ds = New DataSet
                ds.Tables.Add(clsGet.ConvertDataViewToDataSet(dsView).Copy)
                ViewState("Manage") = ds
                gridItem.DataSource = ViewState("Manage")
                gridItem.DataBind()
            Else
                gridItem.DataSource = Nothing
                gridItem.DataBind()
                lbAlert.Text = "ไม่พบรายการ Booking"
            End If
        End If
    End Sub

    Private Sub btnRejectService_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnRejectService.Click
        Dim conn As New System.Data.SqlClient.SqlConnection(connString)
        Dim clsDB As New ClassDatabase
        Dim clsFc As New ClassFunction
        Dim condition As Boolean = True
        Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
        Application.Lock()
        conn.Open()
        tran = clsDB.BeginTran(conn)

        If (clsFc.UPDATEAdd_Tariff_NewStatus(hdfBooking.Value.ToString.Split("$")(0), "R", CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("Name"), Date.Now.ToString("dd MMM yyyy"), Date.Now.ToString("HH:mm"), conn, tran) < 1) Then
            condition = False
        End If

        If (condition) Then
            clsDB.CommitTran(tran)

            ViewState("Owner") = hdfBooking.Value.ToString.Split("$")(1)
            EditBooking(hdfBooking.Value.ToString.Split("$")(0), hdfBooking.Value.ToString.Split("$")(1), hdfBooking.Value.ToString.Split("$")(2), hdfBooking.Value.ToString.Split("$")(3))
        Else
            clsDB.RollBackTran(tran)
        End If
        Application.UnLock()
        conn.Dispose()
    End Sub

    Private Sub btnApproveService_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnApproveService.Click
        Dim conn As New System.Data.SqlClient.SqlConnection(connString)
        Dim clsDB As New ClassDatabase
        Dim clsFc As New ClassFunction
        Dim condition As Boolean = True
        Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
        Dim dtTariff As DataSet = clsGet.Get_BookingTariff(hdfBooking.Value.ToString.Split("$")(0), hdfBooking.Value.ToString.Split("$")(1))
        Dim dtService As DataTable = clsGet.Get_Add_Tariff_New(hdfBooking.Value.ToString.Split("$")(0), "N")
        Application.Lock()
        conn.Open()
        tran = clsDB.BeginTran(conn)
        For Each dr As DataRow In dtService.Rows
            Dim Plant As String = "1104"
            If (hdfBooking.Value.ToString.Split("$")(3) & "" = "L") Then
                Plant = "1103"
            End If
            Dim Owner As String = ""
            If (dtTariff.Tables(0).Rows.Count > 0) Then
                Owner = hdfBooking.Value.ToString.Split("$")(1)
            End If
            Dim dtDetail As DataTable = clsGet.Get_MeterailDefault(dr.Item("Material"), False, "", "", "", "", "", "", "", "", Plant).Tables(0)
            If (clsFc.InsertBookingTariff(dr.Item("MATERIAL"), hdfBooking.Value.ToString.Split("$")(0), dtDetail.Rows(0).Item("Text_line"), dtDetail.Rows(0).Item("Unit"), dr.Item("Count"), "N", dtDetail.Rows(0).Item("KBETR"), dtDetail.Rows(0).Item("KONWA"), "", "Y", "N", Owner, "", conn, tran) < 1) Then
                condition = False
            End If
        Next

        If (clsFc.UPDATEAdd_Tariff_NewStatus(hdfBooking.Value.ToString.Split("$")(0), "A", CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("Name"), Date.Now.ToString("dd MMM yyyy"), Date.Now.ToString("HH:mm"), conn, tran) < 1) Then
            condition = False
        End If

        If (condition) Then
            clsDB.CommitTran(tran)

            ViewState("Owner") = hdfBooking.Value.ToString.Split("$")(1)
            EditBooking(hdfBooking.Value.ToString.Split("$")(0), hdfBooking.Value.ToString.Split("$")(1), hdfBooking.Value.ToString.Split("$")(2), hdfBooking.Value.ToString.Split("$")(2))
        Else
            clsDB.RollBackTran(tran)
        End If
        Application.UnLock()
        conn.Dispose()
    End Sub

    Private Sub MainPage_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
        Dim ds As DataSet = Session("UserData")
        If Not (ds Is Nothing) Then
            Page.MasterPageFile = clsGet.GetMaster_Page(ds.Tables(0).Rows(0).Item("User_Name").ToString(), "M")
        End If
    End Sub

    Private Sub btnSearchVPS_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearchVPS.Click
        LoadBOoking()
        Timer1_Tick(sender, e)
    End Sub

    Private Sub btnVesselLoad_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnVesselLoad.Click
        If Not (Session("VESSEL_OTHER") Is Nothing) Then
            'Try
            '    txtBooking.Text = Session("VESSEL_OTHER").ToString().Split("-")(0)
            'Catch ex As Exception

            'End Try
            Session("VESSEL_OTHER") = Nothing
        End If

    End Sub

    'Private Sub chkShifting_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles chkShifting.CheckedChanged
    '    If (chkShifting.Checked) Then
    '        rowShifting.Visible = True
    '    Else
    '        rowShifting.Visible = False
    '        txtBooking.Text = String.Empty
    '    End If
    'End Sub

    'Private Sub btnBooking_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnBooking.Click
    '    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " document.getElementById('ctl00_contentplaceholder1_iframeVessel').src = '../FormPopup/Vessel_Popup.aspx';", True)
    '    ModalPopupExtenderBB.Show()
    'End Sub

    Private Function SendMail(ByVal Booking_no As String, ByVal ActionBy As String, ByVal Body As String, ByVal Status As String) As Boolean
        Dim Role As String = ""
        If (ActionBy = "VPS") Then
            Role = clsGet.Get_EmailForSend("'00005'") & ";" & clsGet.Get_EmailForSendAgent(Booking_no)
        ElseIf (ActionBy = "MRI") Then
            Role = clsGet.Get_EmailForSend("'00004','00003'") & ";" & clsGet.Get_EmailForSendAgent(Booking_no)
        ElseIf (ActionBy = "MARKETING") Then
            Role = clsGet.Get_EmailForSend("'00004','00005'") & ";" & clsGet.Get_EmailForSendAgent(Booking_no)
        ElseIf (ActionBy = "CANCEL") Then
            Role = clsGet.Get_EmailForSend("'00003','00004','00005'") & ";" & clsGet.Get_EmailForSendAgent(Booking_no)
        End If
        If (Status = "MO") Then
            Role = clsGet.Get_EmailForSend("'00012','00013','00014'") & ";" & clsGet.Get_EmailForSendAgent(Booking_no)
        End If
        Dim test As String = clsFc.sendmail(Role, "", "iPORT", Body, "")
        If (test <> "") Then
            Return True
        Else
            Return False
        End If
    End Function

    Private Function GenBody(ByVal str As String, ByVal booking_no As String, ByVal Agent As String, ByVal Vessel As String, ByVal Laycan As String) As String
        Dim HTML As String = ""
        HTML = "<table width='100%' border='0' cellpadding='2' cellspacing='1'>"
        HTML &= "<tr>"
        HTML &= "<td align='left'><font class='White-Style' font-weight:bold style='color:#000000'>" & str & "</font></td>"
        HTML &= "</tr>"
        HTML &= "</table>"

        HTML &= "<table width='100%' border='0' cellpadding='2' cellspacing='1'>"
        HTML &= "<tr>"
        HTML &= "<td style='width:220px;' align='right'><font class='White-Style' style='color:#000000'>Booking No. :</font>&nbsp;</td>"
        HTML &= "<td align='left'><font class='White-Style' style='color:#000000'>" & booking_no & "</font></td>"
        HTML &= "</tr>"
        HTML &= "<tr>"
        HTML &= "<td style='width:220px;' align='right'><font class='White-Style' style='color:#000000'>Sold To :</font>&nbsp;</td>"
        HTML &= "<td align='left'><font class='White-Style' style='color:#000000'>" & Agent & "</font></td>"
        HTML &= "</tr>"
        HTML &= "<tr>"
        HTML &= "<td style='width:220px;' align='right'><font class='White-Style' style='color:#000000'>Vessel :</font>&nbsp;</td>"
        HTML &= "<td align='left'><font class='White-Style' style='color:#000000'>" & Vessel & "</font></td>"
        HTML &= "</tr>"
        HTML &= "<tr>"
        HTML &= "<td style='width:220px;' align='right'><font class='White-Style' style='color:#000000'>Lay Can\Lay Day :</font>&nbsp;</td>"
        HTML &= "<td align='left'><font class='White-Style' style='color:#000000'>" & Laycan & "</font></td>"
        HTML &= "</tr>"
        HTML &= "</table>"
        Return HTML
    End Function

    Private Sub btnReloadVessel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnReloadVessel.Click
        'ทำการค้นหาข้อมูลเรือและทำการอัพเดตเรือแทข้อมูลที่ Dummy ไว้
        Try
            Dim ds As DataTable = clsGet.Get_VEHICLE_DETAIL(lbVehicle.Text.Split("-")(0))
            If (ds.Rows.Count = 1) Then
                'พบข้อมูลเรือ
                Dim conn As New System.Data.SqlClient.SqlConnection(connString)
                Dim clsDB As New ClassDatabase
                Dim clsFc As New ClassFunction
                Dim condition As Boolean = True
                Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
                Dim ds_Log As DataTable = clsGet.Get_Booking_LOG(ViewState("EditBooking"))
                Dim Vps As String = CType(Session("UserData"), DataSet).Tables(0).Rows(0).Item("User_name") & " " & DateTime.Now.ToString("yyyyMMdd:HHmmss")
                Application.Lock()
                conn.Open()

                Dim Booking_Log As String = Date.Now.ToString("yyyyMMddHHmmss")
                tran = clsDB.BeginTran(conn)
                Try
                    If (clsFc.UpdateBookingVehicle(ViewState("EditBooking"), ds.Rows(0).Item("VEHICLE"), ds.Rows(0).Item("VEH_TEXT"), (CDbl(ds.Rows(0).Item("VEH_LENGTH").ToString().Trim()) * 3.281).ToString("##########0.00"), ds.Rows(0).Item("VEH_MAXWGT_C").ToString().Trim(), (CDbl(ds.Rows(0).Item("DRAFT").ToString().Trim()) * 3.281).ToString("##########0.00"), ds.Rows(0).Item("STCMNR").ToString().Trim().Replace("GRT", "").Replace("=", "").Replace("MT", ""), ds.Rows(0).Item("REG_CNTRY") & "", conn, tran) < 1) Then
                        condition = False
                    End If
                    If (condition) Then
                        clsDB.CommitTran(tran)

                        lbVehicle.Text = ds.Rows(0).Item("VEHICLE") & "-" & ds.Rows(0).Item("VEH_TEXT")
                        lbLOA.Text = (CDbl(ds.Rows(0).Item("VEH_LENGTH").ToString().Trim()) * 3.281).ToString("##########0.00")
                        lbDWT.Text = ds.Rows(0).Item("VEH_MAXWGT_C").ToString().Trim()
                        lbDraft.Text = (CDbl(ds.Rows(0).Item("DRAFT").ToString().Trim()) * 3.281).ToString("##########0.00")
                        lbGRT.Text = ds.Rows(0).Item("STCMNR").ToString().Trim().Replace("GRT", "").Replace("=", "").Replace("MT", "")
                        lbNation.Text = ds.Rows(0).Item("REG_CNTRY") & ""
                        rowVehicle.Visible = False
                        ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('บันทึกข้อมูลเรือสำเร็จ');", True)
                    Else
                        clsDB.RollBackTran(tran)
                        ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการบันทึก');", True)
                    End If
                Catch ex As Exception
                    clsDB.RollBackTran(tran)
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการบันทึก');", True)
                End Try
                Application.UnLock()
                conn.Dispose()
            Else
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ไม่พบข้อมูลเรือ!!');", True)
            End If
        Catch ex As Exception

        End Try

    End Sub

    Private Sub btnUPdateBillTo_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUPdateBillTo.Click
        Dim Bill_To_no As String = ""
        Dim Bill_To_name As String = ""
        If (txtBillTo.Text.Trim() <> "") Then
            Bill_To_no = txtBillTo.Text.Split("-")(0)
            Bill_To_name = txtBillTo.Text.Split("-")(1)
        End If
        Dim dsBooking As DataTable = clsGet.Get_BookingOneRecord(ViewState("EditBooking")).Tables(0)
        Dim ChkOwner As Boolean = False
        Try
            If (clsGet.Get_Bill_TO_Bulk(ViewState("EditBooking") & "", ViewState("Owner") & "") <> "0") Then
                ChkOwner = True
            End If
        Catch ex As Exception

        End Try
        Dim conn As New System.Data.SqlClient.SqlConnection(connString)
        Dim clsDB As New ClassDatabase
        Dim clsFc As New ClassFunction
        Dim condition As Boolean = True
        Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
        Application.Lock()
        conn.Open()

        Dim Booking_Log As String = Date.Now.ToString("yyyyMMddHHmmss")
        tran = clsDB.BeginTran(conn)

        If (ViewState("PORT") = "L") Then
            If (clsFc.UpdateBooking_Bill_to(ViewState("EditBooking"), Bill_To_no, Bill_To_name, conn, tran) < 1) Then
                condition = False
            End If
        Else
            If (dsBooking.Rows(0).Item("MAgent_no") & "" <> ViewState("Owner") & "") Or (ChkOwner) Then
                'Owner
                If (clsFc.UpdateTariffOwnerBillTo(ViewState("EditBooking"), ViewState("Owner"), Bill_To_no, Bill_To_name, conn, tran) < 1) Then
                    condition = False
                End If
            Else
                If (clsFc.UpdateBooking_Bill_to(ViewState("EditBooking"), Bill_To_no, Bill_To_name, conn, tran) < 1) Then
                    condition = False
                End If
            End If
        End If
        If (condition) Then
            clsDB.CommitTran(tran)
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('บันทึกข้อมูล Bill To สำเร็จ');", True)
        Else
            clsDB.RollBackTran(tran)
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('เกิดความผิดพลาดในการบันทึก');", True)
        End If
    End Sub

    Protected Sub btnApproveAll_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnApproveAll.Click
        'Application.Lock()

        Dim booking_no As String = ""
        Dim s As String = ""
        For Each gvr As GridViewRow In gridItem.Rows

            If gvr.RowType = DataControlRowType.DataRow Then
                booking_no = gridItem.DataKeys(gvr.RowIndex)("Booking_no").ToString()
                Dim chkBox As CheckBox = New CheckBox()
                chkBox = CType(gvr.FindControl("checkApprove"), CheckBox)
                'If chkBox.Enabled And chkBox.Checked Then
                '    s &= booking_no & " is Checked<br>"
                'Else
                '    s &= booking_no & " isn't Checked<br>"
                'End If
                If chkBox.Checked And chkBox.Enabled Then
                    If (Session("Role") & "" = "00004") Then
                        'VPS
                        UpdateStatus("VA", booking_no)
                    ElseIf (Session("Role") & "" = "00005") Then
                        'MRI
                        If (rowVehicle.Visible) Then
                            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการ Update ข้อมูลเรือก่อนทำการอนุมัติ !!');", True)
                        Else
                            Dim dtBooking As DataTable = clsGet.Get_BookingOneRecord(booking_no).Tables(0)
                            If (dtBooking.Rows(0).Item("Marketing_approve") & "" = "") Then
                                UpdateStatus("MA", booking_no)
                                's &= booking_no & " MA<br>"
                            Else
                                UpdateStatus("MO", booking_no)
                                's &= booking_no & " MO<br>"
                            End If

                        End If
                    End If
                End If

            End If

        Next
        test_label.Text = s
        'Application.UnLock()
        LoadBOoking()
        ' Timer1_Tick(sender, e)
    End Sub


End Class